4

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|

3
  • 1
    No, but it's very simple to write one. Commented Nov 14, 2013 at 0:33
  • I know that it is very simple, but I've asked about existing function. If not, I will accept answer with implementation. Commented Nov 14, 2013 at 0:40
  • Well, if you know where the end of the array is, then yes technically there is: memmove. I take it we're talking about an array where you know the size, rather than a null-terminated string. Commented Nov 14, 2013 at 0:42

2 Answers 2

8

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 );
    }
}
Sign up to request clarification or add additional context in comments.

Comments

6

You can make one:

void remove_elt(char *str, int i) {
    int len = strlen(str);

    for (; i < len - 1 ; i++)
    {
       str[i] = str[i+1];
    }

    str[i] = '\0';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.