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;
}
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';
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments