Добавление и удаление элементов

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

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");
}

//memmove shifts the tail (the areas overlap, so not memcpy)
void insertAt(int arr[], size_t *count, size_t index, int value) {
    memmove(&arr[index + 1], &arr[index], (*count - index) * sizeof arr[0]);
    arr[index] = value;
    (*count)++;
}

void removeAt(int arr[], size_t *count, size_t index) {
    memmove(&arr[index], &arr[index + 1], (*count - index - 1) * sizeof arr[0]);
    (*count)--;
}

//the size of a C array is fixed: keep spare room
//and the number of the elements in use
int nums[10] = {2, 5, 7};
size_t count = 3;

nums[count++] = 11;
//nums is {2, 5, 7, 11}
printArray("nums", nums, count);

insertAt(nums, &count, 1, 3);
//nums is {2, 3, 5, 7, 11}
printArray("nums", nums, count);

removeAt(nums, &count, 2);
//nums is {2, 3, 7, 11}
printArray("nums", nums, count);

int more[] = {13, 17};
memcpy(&nums[count], more, sizeof more);
count += sizeof more / sizeof more[0];
//nums is {2, 3, 7, 11, 13, 17}
printArray("nums", nums, count);

//clearing changes only the count
count = 0;
//nums is {}
printArray("nums", nums, count);