Search code examples
cfunctionvector

Is it possible to remove an element in a vector in C?


I've a problem with an exercise. It asks "Write a function that gets a vector and returns the vector removing any prime numbers". There's also a suggestion, "Remove an i-th element in a vector means move from the i+1-th element to the (N-1)-th element to cover the empty spot left from the deleted element". And I can't use any pointer.

I don't know how to do it.


Solution

  • Write a function that gets a vector

    There is no such thing as a vector type in C. Probably it's an array.

    And I can't use any pointer

    hmmm... passing an array to a function in C is actually "passing a pointer" so it will be very difficult to avoid. But the function can be written so that it kind of hides the use of a pointer.

    Now for the code, the function could look like:

    size_t remove_primes(size_t size, int a[]);
    

    That is a function taking an array and it's size as arguments and returns the new size after primes has been removed.

    In code it could be something like:

    size_t remove_primes(size_t size, int a[])
    {
        size_t i = 0;
        while ( i < size)
        {
            if (is_prime(a[i]))
            {
                // It's a prime so move all element after i'th element to the left
                //
                // memmove(&a[i], &a[i+i], (size - 1 - i) * sizeof a[0]);
                //
                // or to hide use of pointers
                //
                for (size_t j = i+1; j < size; ++j) a[j-1] = a[j];
    
                --size;
            }
            else
            {
                ++i;
            }
        }
        return size;
    }
    

    or for better performance like:

    size_t remove_primes(size_t size, int a[])
    {
        size_t writer = 0;
        for (size_t reader = 0; reader < size; ++reader)
        {
            if ( ! is_prime(a[reader]))
            {
                // Not a prime so save the value
                a[writer] = a[reader];
                ++writer;
            }
        }
        return writer;
    }