Home > Blockchain >  Deleting occurrences of an element in an array in C
Deleting occurrences of an element in an array in C

Time:08-16

This C code is for deleting all occurrences of an integer in an array. However, when I executed it, there is a problem with displaying the final array, the code doesn't display the rest of the array once it finds the first occurrence.

unsigned int T[10], n, i, j, exist, integerDeleteOccurences;

printf("Array length : ");
scanf("%u", &n);

for(i=0; i<n; i  )
{
    printf("%u | ", T[i]);
}

printf("The number you want to delete its occurences : ");
scanf("%u", &integerDeleteOccurences);

exist = 0;

for (i=0; i<n; i  )
{
    if (T[i] == integerDeleteOccurences)
    {
        j = i;
        for (j=i; j<n-1; j  );
        {
            T[j] = T[j 1];
        }
        exist = 1;
        i--;
        n--;
    }
}

if (exist == 1)
{
    for (i=0; i<n; i  )
    {
        printf("%u | ", T[i]);
    }
}

else if (exist == 0)
{
    printf("This number doesn't exist in the array ! \n");
}

CodePudding user response:

When working with statically allocated arrays (i.e. you know the maximum possible size), you should handle them by keeping track of their current size. Here's some code of how you could delete all occurrencies of an element, given an array and its size:

#include <stdio.h>

#define MAX_SIZE 10

int deleteAllOccurrencies(int* arr, int size, int el)
{
    int occurrencies = 0;

    for (int i = 0; i < size; i  )
    {
        if (arr[i] == el)
        {
            occurrencies  ;
            
            // shift following elements
            for (int j = i; j < size; j  )
            {
                arr[j] = arr[j   1];
            }
        }
    }

    return occurrencies;
}

void printArray(int arr[], int size)
{
    printf("[ ");
    for (int i = 0; i < size; i  )
    {
        printf("%d", arr[i]);
        if (i < size - 1)
            printf(", ");
    }
    printf("]\n");
}

int main(int argc, char** argv)
{
    int array[MAX_SIZE] = { 1, 2, 3, 4, 2, 6, 7, 8, 2, 10 };
    int size = MAX_SIZE;

    printf("Array before: ");
    printArray(array, size);
    
    size = deleteAllOccurrencies(array, size, 2);
    
    printf("Array after: ");
    printArray(array, MAX_SIZE - size);
    printf("Result: %d occurrencies found\n", size);

    return 0;
}

CodePudding user response:

It is far to complicated.

size_t removeFromArray(int *arr, size_t size, int val)
{
    int *tail = arr;
    size_t newSize = size;
    if(arr && size)
    {
        while(size--)
        {
            if(*tail == val) { tail  ; newSize--;}
            else 
                *arr   = *tail  ;
        }
    }
    return newSize;
}
  • Related