Reputation: 9512
I'm looking at some existing code and added a few printf lines. There's a string cp "TZ=test"
cp = strchr(str, '=');
printf("Text: %s\n",cp);
printf("Text cp+1: %s\n",cp+1);
*cp = '\0';
printf("Text: %s\n",cp);
printf("Text cp+1: %s\n",cp+1);
the output is:
Text: =test
Text c+1: test
Text:
Text c+1: test
I understand the first two tests but why does the fourth one print "test" even though *cp was set to '\0' right before?
Upvotes: 0
Views: 130
Reputation: 318688
Setting a character to \0
will terminate the string before it at this point since \0
is the string end character in C.
Anything after it is not affected by it, so it is a great way to avoid allocating more memory when splitting a string since you can just replace the separator with \0
and then use the original pointer to the beginning of the string to get the first part, and sep + 1
to get the second part.
Upvotes: 2
Reputation: 8164
Because you are only setting the first character of the string to \0
. The rest of the memory is untouched. So printing from *cp + 1
begins printing from Test
and not from \0Test
.
Upvotes: 2
Reputation: 62459
It is irrelevant whether you set cp[0]
to '\0'. You are printing cp+1
which is still "test".
Upvotes: 2
Reputation: 137412
Unlike some other languages, C doesn't know what string is, it only knows where it ends, so it prints from the pointer that you give it.
[=test\0]
1: ^start here
^ end at \0
2: ^start here
^ end at \0
[\0test\0]
3: ^start here, it's \0, so stop
4: ^start here
^ end at \0
Upvotes: 3
Reputation: 20036
Because you're printing *cp+1.
Here's what cp looked like before:
=test
^^^^^^^^
and here's after
test
^^^^^^^^
You only overwrote the first character.
Upvotes: 2