简体   繁体   中英

How do I remove the first n characters from a string in c?

I have a function drop_left() that removes the first n characters from the string. I increment the pointer n spaces so that the string points to the everything after the first n characters. When I return to main, the function did not actually change the string. What am I doing wrong?

int main(int argc, char** argv) {
    char string[]="drop left";
    drop_left(string, 2);
    printf("Drop left: %s\n" , string);
}

void drop_left(char *s, int n){
        s+=n;
}   

Because you're modifying s inside your function, which does NOTHING for the pointer to the string OUTSIDE of the function. You'd need to return s inside the function, then string = drop_left(string, 2) .

And note that doing this will cause memory leaks. Your code is simply causing C to "forget" about the dropped characters, but they'll still be using up memory and cause troubles if you do the same sort of thing on strings for which you've malloc()'d the space.

When you change s in drop_left , you are changing a local variable. It does not change where the original string points to in the calling function.

One way to deal with it is to change the contents of the string in order see the change in the calling function. You can use something like:

void drop_left(char *s, int n)
{
   char* s2 = s + n;
   while ( *s2 )
   {
      *s = *s2;
      ++s;
      ++s2;
   }
   *s = '\0';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM