//a growing array: the elements, how many are in use and room for how many
typedef struct {
int *items;
size_t count;
size_t capacity;
} IntArray;
//adds to the end; when the room runs out, realloc doubles it
bool append(IntArray *arr, int value) {
if (arr->count == arr->capacity) {
size_t capacity = arr->capacity == 0 ? 4 : arr->capacity * 2;
int *items = realloc(arr->items, capacity * sizeof items[0]);
if (items == nullptr) {
return false; //no memory, the old elements are still there
}
arr->items = items;
arr->capacity = capacity;
}
arr->items[arr->count++] = value;
return true;
}
void printArray(const char *name, const int arr[], size_t count) {
printf("%s is {", name);
for (size_t i = 0; i < count; i++) {
if (i > 0) {
printf(", ");
}
printf("%d", arr[i]);
}
printf("}\n");
}
//the size is known only at run time: the memory comes from the heap,
//calloc fills it with zeros
size_t count = 5;
int *lstInt = calloc(count, sizeof lstInt[0]);
lstInt[0] = 1;
//lstInt is {1, 0, 0, 0, 0}
printArray("lstInt", lstInt, count);
free(lstInt);
IntArray squares = {};
for (int i = 1; i <= 10; i++) {
append(&squares, i * i);
}
//squares.count is 10, squares.capacity is 16
//squares.items[9] is 100
printf("squares.count is %zu\n", squares.count);
printf("squares.capacity is %zu\n", squares.capacity);
printf("squares.items[9] is %d\n", squares.items[9]);
free(squares.items);