Example 1 — Allocate five ints and fill with squares
Use the memory like an array, then release it.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t n = 5;
int *sq = malloc(n * sizeof *sq);
if (sq == NULL) {
fprintf(stderr, "out of memory\n");
return 1;
}
for (size_t i = 0; i < n; i++) sq[i] = (int)(i * i);
for (size_t i = 0; i < n; i++) printf("%d ", sq[i]);
printf("\n");
free(sq);
return 0;
} How It Works
sizeof *sqstays correct if the pointer type changes.- The
NULLcheck prevents writing through a failed allocation. - The block is released with
free.
