Динамические массивы

Массивы и коллекции / Массивы

//растущий массив: элементы, сколько из них занято и на сколько хватит места
typedef struct {
    int *items;
    size_t count;
    size_t capacity;
} IntArray;

//добавляет в конец; когда место кончается, realloc удваивает его
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; //памяти нет, старые элементы остались на месте
        }
        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");
}

//размер известен только во время выполнения: память берётся из кучи,
//calloc заполняет её нулями
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);