0Pricing
C Academy · Lesson

Allocating an Array

Reserve heap memory.

Why Dynamic Arrays?

A normal array has a fixed size set at compile time. But often you don't know how many elements you need until the program runs.

Dynamic arrays solve this: you ask the operating system for a block of memory at runtime using malloc, and you decide the size with a variable.

Meet malloc

malloc (memory allocate) lives in <stdlib.h>. You pass it a number of bytes and it returns a pointer to that block, or NULL if it fails.

The memory comes from the heap and stays alive until you free it.

int *p = malloc(10 * sizeof(int));

All lessons in this course

  1. Allocating an Array
  2. Growing with realloc
  3. A Reusable Vector Type
  4. Freeing and Avoiding Leaks
← Back to C Academy