C Programming: Memory, Pointers and the Stack ยท Dynamic Memory
Ask for memory on the heap at run time, use it like an array, and give it back with free.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = 3;
int *scores = malloc(n * sizeof(int)); /* memory on the heap, size chosen at run time */
if (scores == NULL) {
return 1;
}
for (int i = 0; i < n; i++) {
scores[i] = (i + 1) * 10;
}
int total = scores[0] + scores[1] + scores[2];
free(scores); /* give the memory back */
scores = NULL; /* so it is not used by mistake */
printf("%d\n", total);
return 0;
}n is created on the stack with the value 3.i is created on the stack with the value 0.i changes from 0 to 1.scores points to, index 1 changes from ? to 20.i changes from 1 to 2.scores points to, index 2 changes from ? to 30.i goes out of scope and disappears.total is created on the stack with the value 60.60.0.