calloc
calloc is similar to malloc, but the main difference is that the values stored in the allocated memory space is zero by default. With malloc, the allocated memory could have any value.calloc requires two arguments. The first is the number of variables you'd like to allocate memory for. The second is the size of each variable.
Like malloc, calloc will return a void pointer if the memory allocation was successful, else it'll return a NULL pointer.
This example shows you how to call calloc and also how to reference the allocated memory using an array index. The initial value of the allocated memory is printed out in the for loop.
#include
#include
/* required for the malloc, calloc and free functions */
int main() {
float *calloc1, *calloc2, *malloc1, *malloc2;
int i;
calloc1 = calloc(3, sizeof(float)); /* might need to cast */
calloc2 = calloc(3, sizeof(float));
malloc1 = malloc(3 * sizeof(float));
malloc2 = malloc(3 * sizeof(float));
if(calloc1!=NULL && calloc2!=NULL && malloc1!=NULL && malloc2!=NULL) {
for(i=0 ; i<3 ; i++) {
printf("calloc1[%d] holds %05.5f, ", i, calloc1[i]);
printf("malloc1[%d] holds %05.5f\n", i, malloc1[i]);
printf("calloc2[%d] holds %05.5f, ", i, *(calloc2+i));
printf("malloc2[%d] holds %05.5f\n", i, *(malloc2+i));
}
free(calloc1);
free(calloc2);
free(malloc1);
free(malloc2);
return 0;
}
else {
printf("Not enough memory\n");
return 1;
}
}
Output: calloc1[0] holds 0.00000, malloc1[0] holds -431602080.00000 |
Try changing the data type from float to double - the numbers displayed were too long for me to fit onto this web page :)
No comments:
Post a Comment