MastRofDsastR MastRofDsastR - 2 months ago 5
C Question

C: removing from a full array and only removing first instance of duplicates

I have an array that I am trying to remove values from, however I run into 2 problems when I try to remove from the array:

1.) When I try to remove from an array that is full, I get a * Stack Smashing Detected * error

2.) when my array has multiple duplicates, I only want to remove the first instance, however it seems to remove a random number of instances.

The code I have for the remove function is as follows:

int Remove(int* array, int arrayLen, int removeNum)
{
int i, j;

for (i = 0; i < arrayLen; i++)
{
if (array[i] == removeNum){
for(j = i; j < arrayLen; j++){
array[j] = array[j+1];
}
arrayLen--;
}
}
return arrayLen;
}


Where removeNum is user selected in main().

Answer

I see two issues:

  1. You're reading past the end of the list because you're inner loop goes too far. (At j = arrayLen - 1, j + 1 = arrayLen, which is past the end of the array.)
  2. You say you only want to remove the first found element, but your code continues past that point. Adding an early return (or break) fixes that problem.

Here's a fixed version of your code:

int remove(int* array, int arrayLen, int removeNum)
{
    int i, j;

    for (i = 0; i < arrayLen; i++)
    {
        if (array[i] == removeNum) {
            // Stop j at arrayLen - 1, which is the new end of the array
            for(j = i; j < arrayLen - 1; j++) {
                array[j] = array[j + 1];
            }

            // Return the new size
            return arrayLen - 1;
        }
    }

    // If we didn't remove anything, return the original size
    return arrayLen;
}