Remove Element from Array in C
In the C language, arrays are a chunk of contiguous memory space. Deleting a specified element in an array actually involves moving the subsequent elements forward to overwrite the element to be deleted. The specific steps are as follows:
- Create a function to remove a specified element, with parameters including the array name, array length, and the value of the element to be removed.
- Traverse the array to identify the position of the element to be deleted.
- Move all elements after this position forward by one, overwriting the element to be deleted.
- Reduce the length of the array by one, indicating that one element has been deleted.
Here is an example code:
#include <stdio.h>
void deleteElement(int arr[], int length, int element) {
int i, j;
for (i = 0; i < length; i++) {
if (arr[i] == element) {
// 找到要删除的元素位置
for (j = i; j < length - 1; j++) {
// 将后面的元素向前移动
arr[j] = arr[j + 1];
}
break;
}
}
length--; // 数组长度减一
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int length = sizeof(arr) / sizeof(arr[0]);
int element = 3;
deleteElement(arr, length, element);
// 打印删除元素后的数组
for (int i = 0; i < length - 1; i++) {
printf("%d ", arr[i]);
}
return 0;
}
The code above removes element 3 from the array, and the output is: 1 2 4 5.