Dynamic array
- C course
- Intermediate
- Lesson 7/116
- 5 min
Learn to create a dynamic array with malloc.
Dynamic array
A dynamic array is allocated on the heap at runtime. In C the malloc function does this; its return type is void *.
Example: int *arr = malloc(3 * sizeof(int));. This allocates room for three ints and assigns the start address to arr. arr[0], arr[1], arr[2] are now valid elements. To use malloc you must include <stdlib.h>. The allocated memory is later returned with free.
Using a malloc'd array
An array allocated with malloc is used like a normal array. The arr[i] syntax works for both reading and writing. Two things to watch for.
First, malloc returns NULL on failure; for large allocations you should check this. Second, the allocated memory is uninitialized; it may contain garbage. So you should assign elements yourself before using them. When done, return the memory with free(arr);; otherwise a leak occurs.
Practice Create and print a dynamic array
Allocate a three-element array with int *arr = malloc(3 * sizeof(int));. Assign 1, 2, 3 to the elements. Use a for loop to print each element as printf("%d ", arr[i]); then add a newline with printf("\n"). Finally return the memory with free(arr);.
Starter code
#include <stdio.h>
#include <stdlib.h>
// Allocate arr with malloc
// Assign 1, 2, 3 to elements
// Loop, print and free
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *arr = malloc(3 * sizeof(int));
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
for (int i = 0; i < 3; i++) printf("%d ", arr[i]);
printf("\n");
free(arr);
return 0;
}Expected output
1 2 3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which header is required for malloc?
- <stdio.h>
- <stdlib.h> Correct answer
- <string.h>
- <math.h>
Explanation: malloc, free, realloc and calloc are declared in stdlib.h.
2 malloc call for three ints
int *arr = ____(3 * sizeof(int));
int *arr = malloc(3 * sizeof(int));
Explanation: malloc allocates uninitialized memory.
3 Match the malloc parts
| Term | Meaning |
|---|---|
malloc |
Allocator function |
3 * sizeof(int) |
Size expression |
void * |
Return type |
free(arr) |
Memory release |