Lesson 38 of 50
cDynamic Memory – Reallocating Arrays
10 mins
Course progress76%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 38 of 50
c10 mins
Keep these ideas in mind as you work through the lesson.
realloc changes the size of an existing allocation while preserving its content.
int *arr = malloc(5 * sizeof *arr);
/* ... fill ... */
arr = realloc(arr, 10 * sizeof *arr); // grow to 10 elements
If the block cannot be enlarged in place, realloc allocates a new block, copies the old data, frees the old block, and returns the new pointer. Always assign to a temporary variable first to avoid losing the original pointer on failure.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t cap = 4, used = 0;
int *buf = malloc(cap * sizeof *buf);
if (!buf) return 1;
for (int i = 0; i < 12; ++i) {
if (used == cap) {
size_t newCap = cap * 2;
int *tmp = realloc(buf, newCap * sizeof *tmp);
if (!tmp) { free(buf); return 1; }
buf = tmp; cap = newCap;
}
buf[used++] = i * i;
}
for (size_t i = 0; i < used; ++i) printf("%d ", buf[i]);
printf("
");
free(buf);
return 0;
}