calloc, realloc and Dynamic Arrays
calloc allocates zeroed memory, and realloc resizes a block. Always check for NULL and keep the old pointer until realloc succeeds.
Example
int cap = 2, n = 0;
int *v = calloc(cap, sizeof *v);
for (int i = 1; i <= 5; i++) {
if (n == cap) { cap *= 2; int *t = realloc(v, cap * sizeof *v); if (!t) return 1; v = t; }
v[n++] = i * i;
}
for (int i = 0; i < n; i++) printf("%d ", v[i]);
printf("(cap %d)\n", cap);
free(v);Result
1 4 9 16 25 (cap 8)
Exercise
Allocate zeroed memory.
int *v = (4, sizeof *v);
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.