Dave's Brain

Browse - Programming Tips - How can I delete an element from an array in C/C++ ?

Date: 2010may13
Language: C/C++

Q.  How can I delete an element from an array in C/C++ ?

A.  Here is an example of 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)); } void ExampleUse() { THING my_things[20]; // Declare the array // ... // put some stuff into the array // ... // Delete element 5 DeleteArrayElement(a, 5, sizeof(my_things) / sizeof(my_things[0])); }
Use erase() to delete an element from an STL vector (which is a growable array).

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.