How to remove the first string element in array of string

144 Views Asked by At

Assuming I have this array of string

char* arr[] = {"Me", "you", "Now", NULL};

My aim is to remove "Me" so that the resultant array is:

arr = {"you", "Now", NULL};

Is there a way I can do this without running a for loop and store the element in a new array? I have tried increment operation arr++, but I am getting error.

1

There are 1 best solutions below

0
On

The size of the array can not be changed. And arrays are non-modifiable lvalues. They do not have the assignment operator

So this statement

arr = {"you", "Now", NULL};

is incorrect.

What you can do is to move elements of the array to the left. For example

#include <string.h>

//...

char* arr[] = {"Me", "you", "Now", NULL};
const size_t N = sizeof( arr ) / sizeof( *arr );

memmove( arr, arr + 1, ( N - 1 ) * sizeof( *arr ) ); 

Here is a demonstration program.

#include <string.h>
#include <stdio.h>

int main( void )
{
    char *arr[] = { "Me", "you", "Now", NULL };
    const size_t N = sizeof( arr ) / sizeof( *arr );

    for (char **p = arr; *p; ++p)
    {
        printf( "%s ", *p );
    }
    putchar( '\n' );

    memmove( arr, arr + 1, ( N - 1 ) * sizeof( *arr ) );

    for (char **p = arr; *p; ++p)
    {
        printf( "%s ", *p );
    }
    putchar( '\n' );
}

The program output is

Me you Now
you Now

Pay attention to that the arrays still have four elements.