How to remove a specific element from an array in C language?

In C language, the length of an array is fixed and it is not possible to directly remove elements. However, you can achieve this by moving the subsequent elements forward and overwriting the element to be deleted.

Here is an example code showing how to remove an element at a specified position from an array.

#include <stdio.h>

#define SIZE 5

void deleteElement(int arr[], int *size, int index) {
    if (index >= *size) {
        printf("Invalid index\n");
        return;
    }
    
    for (int i = index; i < *size - 1; i++) {
        arr[i] = arr[i + 1];
    }
    
    (*size)--;
}

int main() {
    int arr[SIZE] = {1, 2, 3, 4, 5};
    int size = SIZE;
    
    printf("Original Array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    int index = 2; // 要删除的元素的索引
    deleteElement(arr, &size, index);
    
    printf("Updated Array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    return 0;
}

Output:

Original Array: 1 2 3 4 5 
Updated Array: 1 2 4 5 

In the above example, the deleteElement function takes an array, the size of the array (passed by pointer), and the index of the element to be deleted. The function first checks if the index is valid, then moves the elements after the index forward by one position, and decreases the size of the array by 1.

In the main function, we defined an array of length 5 and initialized it to {1, 2, 3, 4, 5}. We then called the deleteElement function to remove the element at index 2 (the number 3). Finally, we printed the updated array.

Please note that this method only covers the elements to be deleted and does not actually remove them from memory. If you need to dynamically adjust the array length and delete elements, consider using dynamic memory allocation (such as malloc and free functions) to achieve this.

bannerAds