How to add elements to the end of an array in C languag…

In the C language, the size of an array is fixed and cannot be dynamically increased. If you need to add elements to the end of an existing array, you must create a larger array, copy the elements from the original array to the new array, and then add the new elements to the end of the new array.

The specific steps are as follows:

  1. Declare a new array with a size one larger than the original array.
  2. Use a loop to copy each element of the original array to the new array one by one.
  3. Add a new element to the last position of the new array.
  4. Optionally, free the memory of the original array.
  5. Update the pointers of the original array to point to the new array.

Here is a sample code:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int size = 5;  // 原数组的大小
    int* arr = (int*)malloc(size * sizeof(int));
    int i;

    // 初始化原数组
    for (i = 0; i < size; i++) {
        arr[i] = i;
        printf("%d ", arr[i]);
    }
    printf("\n");

    int newSize = size + 1;  // 新数组的大小
    int* newArr = (int*)malloc(newSize * sizeof(int));

    // 将原数组的元素复制到新数组中
    for (i = 0; i < size; i++) {
        newArr[i] = arr[i];
    }

    // 在新数组的末尾添加新元素
    int newElement = 10;
    newArr[newSize - 1] = newElement;

    // 释放原数组的内存
    free(arr);

    // 更新原数组的指针
    arr = newArr;

    // 输出新数组的元素
    for (i = 0; i < newSize; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    free(arr);  // 释放新数组的内存

    return 0;
}

Please note that the above code is just an example of adding a new element to the end of the original array. If you need to add elements at multiple positions or frequently insert and delete elements, it is recommended to use linked lists or other data structures to implement this.

bannerAds