WeCodeAcademy

C Dynamic Arrays with realloc

When you do not know the size in advance, allocate with malloc and grow with realloc. Always check the result and free the memory.

ExampleC
#include <stdio.h>
#include <stdlib.h>

int main(void) {
  int capacity = 2;
  int count = 0;
  int *data = malloc(capacity * sizeof(int));
  if (data == NULL) return 1;

  for (int i = 1; i <= 7; i++) {
    if (count == capacity) {
      capacity *= 2;
      int *bigger = realloc(data, capacity * sizeof(int));
      if (bigger == NULL) { free(data); return 1; }
      data = bigger;
      printf("grew to %d\n", capacity);
    }
    data[count++] = i * i;
  }

  for (int i = 0; i < count; i++) printf("%d ", data[i]);
  printf("\n");
  free(data);
  return 0;
}
Output
grew to 4
grew to 8
1 4 9 16 25 36 49
Quick check

What must you always do with memory from malloc?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.