Date: 2010may13
Update: 2026sep30
Language: C/C++
Q. C/C++: How to delete an element from a regular array in C/C++
A. Here is a function that can do it:
inline void DeleteArrayElement(THING a[], const int i, const int n) {
memmove(&a[i], &a[i+1], (n - i - 1) * sizeof(THING));
}
Use erase() to delete an element from an STL vector (which is a growable array).
Full Example Use:
#include <string.h>
#include <stdio.h>
typedef int THING;
// (Place the above function here)
void PrintArray(const char *label, THING a[], const int n) {
printf("--- %s ---\n", label);
for (int i = 0; i < n; i++) {
printf("[%d]=%d\n", i, a[i]);
}
}
int main() {
THING my_things[6] = {}; // Declare the array and initiaize to zeros
const int n_things = sizeof(my_things) / sizeof(my_things[0]);
// Put some stuff into the array
my_things[0] = 200;
my_things[1] = 300; // We are going to delete this
my_things[2] = 400;
PrintArray("Before delete", my_things, n_things);
DeleteArrayElement(my_things, 1, n_things);
putchar('\n');
PrintArray("After delete", my_things, n_things);
}
Output:
--- Before delete ---
[0]=200
[1]=300
[2]=400
[3]=0
[4]=0
[5]=0
--- After delete ---
[0]=200
[1]=400 // The 300 is now gone
[2]=0
[3]=0
[4]=0
[5]=0