How to remove an element from an array in C?

2020-04-20 21:35发布

问题:

Can't seem to find a way on how to do it....

for example if I have an array

a = { 1,2,3 }

and I want to delete a[1] so the result would be

a = { 1,3 }

How can this be done ?

回答1:

The best you can do is move all of the elements after the removed element up by 1 and keep a size counter that tells you the number of elements currently in the array. A C array is not much more than a block of contiguous memory, and it can't be resized in place.



回答2:

It depends. If the array has been declared as static or has automatic storage duration then you can't do it since you have no way to alter the effective size of the array.

One workaround could be to shift all the elements past the one that is going to be removed to the left and then update a secondary variable used to store the effective length of the array.

If the array has been dynamically allocated then you can just allocate a new, shorter, array. Copy all the elements minus the one that is going to be deleted and you are done.



回答3:

How to remove an element from an array in C?
How can this be done ?

Elements of an array in C cannot be deleted.

An element can be ignored, but not deleted. The sizeof(a) cannot change. Once the array is defined, the number of elements is fixed.

Perhaps a new approach to your higher level task?



回答4:

You could just shift the desired elements depending on the index to delete like so:

Edit: more robust to just copy over to a new array, then would no longer need to ignore last element when just working with one array.

int a = {1, 2, 3};
int new_a[sizeof(a)/sizeof(a[0]) - 1]; // new array will hold one less value
int pos = 3; // delete the item at the third index

for (i = pos - 1; i < sizeof(a)/sizeof(a[0]) - 1; i++) {
    new_a[i] = a[i+1];
}


回答5:

You can't do this with array. Use linked list instead.



标签: c arrays