How to add elements to an array in the C language?
In the C language, the size of an array is fixed and cannot be directly added to. However, you can achieve the effect of adding elements to an array by creating a new array and copying the elements from the original array and the new element into the new array. The specific steps are as follows:
- Declare the original array and a new element: Assume the original array is arr and the new element is newElement.
- Create a new array called newArr with a size one more than the original array arr: int newArr[length + 1];
- Copy the elements from the original array ‘arr’ to the new array ‘newArr’ by iterating through a for loop, assigning the value of ‘arr[i]’ to ‘newArr[i]’.
- Add the new element newElement to the last position in the new array newArr: assign the value of newElement to newArr[length].
- Replace the original array arr with a new array newArr by assigning the address of newArr to arr, like this: arr = newArr;.
- Free the memory of the original array “arr” by using the “free()” function to release the memory space pointed to by “arr”.
Here is a sample code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int length = 5; // 原数组的大小为5
int *arr = (int *)malloc(length * sizeof(int)); // 动态分配内存
int newElement = 6; // 新元素的值为6
// 初始化原数组arr
for (int i = 0; i < length; i++) {
arr[i] = i + 1;
}
// 创建一个新的数组newArr,大小为原数组arr的大小加1
int *newArr = (int *)malloc((length + 1) * sizeof(int));
// 复制原数组arr的元素到新数组newArr中
for (int i = 0; i < length; i++) {
newArr[i] = arr[i];
}
// 在新数组newArr的最后一个位置添加新元素newElement
newArr[length] = newElement;
// 使用新数组newArr替换原数组arr
arr = newArr;
// 输出新数组arr的元素
for (int i = 0; i < length + 1; i++) {
printf("%d ", arr[i]);
}
// 释放原数组arr的内存
free(arr);
return 0;
}
Running the above code will output: 1 2 3 4 5 6, indicating that the new element 6 was successfully added to the array arr.