Home > Enterprise >  How to delete an element from an array in C?
How to delete an element from an array in C?

Time:02-22

I've tried shifting elements backwards but it is not making the array completely empty.

for(i=pos;i<N-count;i  )
        {
            A[i]=A[i 1];
        }

Actually, I've to test for a key value in an input array and if the key value is present in the array then I've to remove it from the array. The loop should be terminated when the array becomes empty. Here "count" represents the number of times before a key value was found and was removed. And, "pos" represents the position of the element to be removed. I think dynamic memory allocation may help but I've not learned it yet.

CodePudding user response:

From your description and code, by "delete" you probably mean shift the values to remove the given element and shorten the list by reducing the total count.

In your example, pos and count would be/should be the similar (off by 1?) .

The limit for your for loop isn't N - count. It is N - 1

So, you want:

for (i = pos; i < (N - 1); i  ) {
    A[i] = A[i   1];
}
N -= 1;

To do a general delete, given some criteria (a function/macro that matches on element(s) to delete, such as match_for_delete below), you can do the match and delete in a single pass on the array:

int isrc = 0;
int idst = 0;

for (;  isrc < N;    isrc) {
    if (match_for_delete(A,isrc,...))
        continue;

    if (isrc > idst)
        A[idst] = A[isrc];

      idst;
}

N = idst;
  • Related