Programming in C

(Barry) #1
Dynamic Memory Allocation 385

The dynamic memory allocation functions are declared in the standard header file


, which should be included in your program whenever you want to use
these routines.

The sizeofOperator


To determine the size of data elements to be reserved by callocor mallocin a
machine-independent way, the C sizeofoperator should be used.The sizeofoperator
returns the size of the specified item in bytes.The argument to the sizeofoperator can
be a variable, an array name, the name of a basic data type, the name of a derived data
type, or an expression. For example, writing


sizeof (int)


gives the number of bytes needed to store an integer. On a Pentium 4 machine, this has
the value 4 because an integer occupies 32 bits on that machine. If xis defined to be an
array of 100 integers, the expression


sizeof (x)


gives the amount of storage required for the 100 integers of x(or the value 400 on a
Pentium 4).The expression


sizeof (struct dataEntry)


has as its value the amount of storage required to store one dataEntrystructure. Finally,
if datais defined as an array of struct dataEntryelements, the expression


sizeof (data) / sizeof (struct dataEntry)


gives the number of elements contained in data(datamust be a previously defined
array, and not a formal parameter or externally referenced array).The expression


sizeof (data) / sizeof (data[0])


also produces the same result.The macro


#define ELEMENTS(x) (sizeof(x) / sizeof(x[0]))


simply generalizes this technique. It enables you to write code like


if ( i >= ELEMENTS (data) )
...


and


for ( i = 0; i < ELEMENTS (data); ++i )
...


You should remember that sizeofis actually an operator, and not a function, even
though it looks like a function.This operator is evaluated at compile time and not at
runtime, unless a variable-length array is used in its argument. If such an array is not
used, the compiler evaluates the value of the sizeofexpression and replaces it with the
result of the calculation, which is treated as a constant.

Free download pdf