malloc()
malloc
-> Memory Allocation (allocate memory on the heap)malloc
ptr = (cast-type*) malloc(byte-size)
#include <stdio.h>
int main(void) {
malloc(1000);
malloc(sizeof(int));
malloc(sizeof(char) * 50);
return 0;
}
malloc()
free()
realloc()
All require stdlib.h
sizeof()
A common way of using malloc is to create dynamic arrays:
int main(void) {
int num_elements;
scanf("%d", num_elements);
int *data = malloc(num_elements * sizeof(int));
data[0] = 5;
return 0;
}
Arrays are contiguous, so we use the address of the first index to access each element
array variable points to start
Move along the sizeof(int)
Move along the sizeof(int)
Where growing memory was cheap
We use a struct on the heap
11, 8, 7
main