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|
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 );
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With