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
- Allocating an Array
- Growing with realloc
- A Reusable Vector Type
- Freeing and Avoiding Leaks