C Programming: Memory, Pointers and the Stack · Dynamic Memory
Start small, and when the array is full, double its capacity with realloc. This is how dynamic arrays grow.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int capacity = 2;
int size = 0;
int *items = malloc(capacity * sizeof(int));
for (int v = 5; v <= 20; v += 5) {
if (size == capacity) {
capacity *= 2;
items = realloc(items, capacity * sizeof(int)); /* grow the block */
}
items[size] = v;
size++;
}
printf("size=%d capacity=%d last=%d\n", size, capacity, items[size - 1]);
free(items);
return 0;
}capacity is created on the stack with the value 2.size is created on the stack with the value 0.v is created on the stack with the value 5.size == capacity to decide which way the code goes.items points to, index 0 changes from ? to 5.size changes from 0 to 1.v changes from 5 to 10.size == capacity to decide which way the code goes.items points to, index 1 changes from ? to 10.size changes from 1 to 2.v changes from 10 to 15.size == capacity to decide which way the code goes.items points to, index 2 changes from ? to 15.size changes from 2 to 3.v changes from 15 to 20.size == capacity to decide which way the code goes.items points to, index 3 changes from ? to 20.size changes from 3 to 4.v goes out of scope and disappears.size=4 capacity=4 last=20.items changes from [5, 10, 15, 20] to → freed memory (dangling).0.