logo

Why double the array size when resizing arrays?

#include <stdio.h> #include <stdlib.h> void add_to_array(int** arr, int* last_index, int* capacity, int elem) { if (*last_index >= *capacity) { int* realloc_result = realloc(*arr, sizeof(int) * (*capacity * 2)); printf("We reallocated\n"); if (realloc_result == NULL) { free(*arr); printf("Realloc failed for arr\n"); exit(1); } *capacity *= 2; *arr = realloc_result; } (*arr)[*last_index] = elem; (*last_index)++; } int main(int argc, char *argv[]) { int capacity = 16; int* arr = malloc(sizeof(int) * capacity); int last_index = 0; add_to_array(&arr, &last_index, &capacity, 17); add_to_array(&arr, &last_index, &capacity, 18); add_to_array(&arr, &last_index, &capacity, 19); add_to_array(&arr, &last_index, &capacity, 20); add_to_array(&arr, &last_index, &capacity, 21); add_to_array(&arr, &last_index, &capacity, 22); add_to_array(&arr, &last_index, &capacity, 23); add_to_array(&arr, &last_index, &capacity, 24); add_to_array(&arr, &last_index, &capacity, 25); add_to_array(&arr, &last_index, &capacity, 26); add_to_array(&arr, &last_index, &capacity, 27); add_to_array(&arr, &last_index, &capacity, 28); add_to_array(&arr, &last_index, &capacity, 29); add_to_array(&arr, &last_index, &capacity, 30); add_to_array(&arr, &last_index, &capacity, 31); add_to_array(&arr, &last_index, &capacity, 32); add_to_array(&arr, &last_index, &capacity, 33); add_to_array(&arr, &last_index, &capacity, 34); add_to_array(&arr, &last_index, &capacity, 35); add_to_array(&arr, &last_index, &capacity, 36); add_to_array(&arr, &last_index, &capacity, 37); add_to_array(&arr, &last_index, &capacity, 38); add_to_array(&arr, &last_index, &capacity, 39); add_to_array(&arr, &last_index, &capacity, 40); add_to_array(&arr, &last_index, &capacity, 41); add_to_array(&arr, &last_index, &capacity, 42); add_to_array(&arr, &last_index, &capacity, 43); add_to_array(&arr, &last_index, &capacity, 44); add_to_array(&arr, &last_index, &capacity, 45); add_to_array(&arr, &last_index, &capacity, 46); add_to_array(&arr, &last_index, &capacity, 47); add_to_array(&arr, &last_index, &capacity, 48); add_to_array(&arr, &last_index, &capacity, 49); add_to_array(&arr, &last_index, &capacity, 50); add_to_array(&arr, &last_index, &capacity, 51); printf("Capacity: %d\n", capacity); printf("Last Index: %d\n", last_index); printf("First element: %d\n", arr[0]); printf("Last element: %d\n", arr[last_index - 1]); free(arr); return 0; }