386 Chapter 17 Miscellaneous and Advanced Features
Use the sizeofoperator wherever possible to avoid having to calculate and hard-
code sizes into your program.
Getting back to dynamic memory allocation, if you want to allocate enough storage
in your program to store 1,000 integers, you can call callocas follows:
#include <stdlib.h>
...
int *intPtr;
...
intPtr = (int *) calloc (sizeof (int), 1000);
Using malloc, the function call looks like this:
intPtr = (int *) malloc (1000 * sizeof (int));
Remember that both mallocand callocare defined to return a pointer to voidand, as
noted, this pointer should be type cast to the appropriate pointer type. In the preceding
example, the pointer is type cast to an integer pointer and then assigned to intPtr.
If you ask for more memory than the system has available,calloc(or malloc) returns
a null pointer.Whether you use callocor malloc, be certain to test the pointer that is
returned to ensure that the allocation succeeded.
The following code segment allocates space for 1,000 integer pointers and tests the
pointer that is returned. If the allocation fails, the program writes an error message to
standard error and then exits.
#include <stdlib.h>
#include <stdio.h>
...
int *intPtr;
...
intptr = (int *) calloc (sizeof (int), 1000);
if ( intPtr == NULL )
{
fprintf (stderr, "calloc failed\n");
exit (EXIT_FAILURE);
}
If the allocation succeeds, the integer pointer variable intPtrcan be used as if it were
pointing to an array of 1,000 integers. So, to set all 1,000 elements to –1, you could
write
for ( p = intPtr; p < intPtr + 1000; ++p )
*p = -1;
assuming pis declared to be an integer pointer.
To r eserve storage for nelements of type struct dataEntry,you first need to define
a pointer of the appropriate type
struct dataEntry *dataPtr;