Reputation: 15045
void slice_first_char(char ** string)
{
*string = &(*string[1]);
}
int main(int argc, char * argv[])
{
char * input = "abc";
input = &(input[1]);
puts(input); // "bc" as expected.
slice_first_char(&input);
puts(input); // \372\277_\377
// What‘s going on?
}
How can I rewrite a slice_first_char function to make it work as expected?
Upvotes: 0
Views: 2224
Reputation: 11241
You seem to be attempting to remove the first char from a string. So:
char* remove_first_char(const char* s) {
return (s+1);
}
Upvotes: 3
Reputation: 94349
You got the parentheses in
&(*string[1]);
wrong. I guess you meant
&((*string)[1]);
Your original version dereferences the pointer of the first element of the strings
array, and then takes the address of that whereas you actually want to dereference the given pointer (because it just points to a single string), then take the first element of that (the first character) and then take the address of that.
A slighty less convulated way to express this would be
*string + 1
by the way.
Upvotes: 11