|
However:
|
|
|
|
calloc( nElems, nBytes ) Example: calloc( 10, 8 ) // Allocate space for 10 elements of size 8 (= array of 10 double) |
The calloc function:
|
int main(int argc, char *argv[]) { int i; double* p; // We uses this reference variable to access // dynamically created array elements p = calloc(10, sizeof(double) ); // Make double array of 10 elements for ( i = 0; i < 10; i++ ) *(p + i) = i; // put value i in array element i for ( i = 0; i < 10; i++ ) printf("*(p + %d) = %lf\n", i, *(p+i) ); free(p); // Un-reserve the first array putchar('\n'); p = calloc(4, sizeof(double) ); // Make a NEW double array of 4 elements // ***** Notice that the array size has CHANGED !!! **** for ( i = 0; i < 4; i++ ) *(p + i) = i*i; // put value i*i in array element i for ( i = 0; i < 4; i++ ) printf("*(p + %d) = %lf\n", i, *(p+i) ); free(p); // Un-reserve the second array } |
Output:
*(p + 0) = 0.000000 *(p + 1) = 1.000000 *(p + 2) = 2.000000 *(p + 3) = 3.000000 *(p + 4) = 4.000000 *(p + 5) = 5.000000 *(p + 6) = 6.000000 *(p + 7) = 7.000000 *(p + 8) = 8.000000 *(p + 9) = 9.000000 *(p + 0) = 0.000000 *(p + 1) = 1.000000 *(p + 2) = 4.000000 *(p + 3) = 9.000000 |
How to run the program:
|