Pointers & Memory · intermediate · ~8 min
Allocate a zeroed integer array and distinguish zeroed bytes from arbitrary object initialization.
calloc takes an element count and an element size, then allocates storage with every byte set to zero. For the integer arrays in this lesson that gives zero-valued elements. You still need an allocation-failure check and an owner who eventually calls free.
Use calloc(n, sizeof *p) for n elements. The two arguments describe the requested array without a multiplication in the call expression. Check the result before access.
All-bits-zero represents integer zero. Do not generalize this into a portable guarantee that zeroed bytes represent every floating-point zero or every null pointer.
The pilot exercise defines n <= 0 as an empty request returning NULL. That is the exercise's chosen contract, not a claim that every call to calloc with a zero count must return NULL.
calloc takes an element count and an element size, then allocates storage with every byte set to zero. For the integer arrays in this lesson that gives zero-valued elements. You still need an allocation-failure check and an owner who eventually calls free.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = calloc(3, sizeof *p);
if (p == NULL) return 1;
printf("%d %d %d\n", p[0], p[1], p[2]);
free(p);
return 0;
}
Expected output on a successful allocation, where applicable:
0 0 0
calloc initializes the bytes for three ints. The program verifies allocation before reading any element, then frees the returned block once.
calloc zeroes bytes and returns owned allocated storage. Check for failure. Integer zero initialization does not imply a universal representation rule for all C types.