Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove nth element from array (char *)

Tags:

arrays

c

Is there any C function that remove N-th element from char* (considering char* as array)?

Example:

char* tab --> |5|4|5|1|8|3|

remove_elt(tab, 3) --> 5|4|5|8|3|

like image 357
JosephConrad Avatar asked Dec 08 '22 11:12

JosephConrad


1 Answers

The question as posed is a little unclear. You suggest it's not a string, but you don't specify the array size in your imaginary function call. That would lead to the current answer which treats the data as a null-terminated string.

An improved version of that answer would recognise that you don't need to call strlen:

void remove_elt(char *str, int i)
{
    for(; str[i]; i++) str[i] = str[i+1];
}

But if it's an array where you store the size (rather than using 0 as an end-marker), then you would need to supply that size to your function. In that case, you could use memmove which can copy overlapping memory:

void remove_elt( char *str, int elem, int *size )
{
    if( elem < --*size ) {
        memmove( &str[elem], &str[elem + 1], *size - elem );
    }
}
like image 67
paddy Avatar answered Dec 11 '22 09:12

paddy