Given for example a char *p that points to the first character in "there is so \0ma\0ny \0 \\0 in t\0his stri\0ng !\0\0\0\0",
how would Strrchr() find the last occurrence of null-character?
the following questions arises:
=>What conditions would it depend on to stop the loop!
=>I think in all cases it'll try to access the next memory area to check for its condition?at some point bypassing the string boundaries, UB! so is it safe !
please if i'am wrong feel free to correct me!
It's very simple, as explained in the comments. The first
\0is the last and the only one in a C string.So if you write
it will print
because
strchrwill find the 's' in "so", which is the last 's' in the string you gave it. And (to answer your specific question) if you writeit will print
proving that
strchrfound the first\0.It's obvious to you that
stris a long string with some embedded\0's in it. But, in C, there is no such thing as a "string with embedded\0's in it". It is impossible, by definition, for a C string to contain an embedded\0. The first\0, by definition, ends the string.One more point. You had mentioned that if you were to "access the next memory area", that you would "at some point bypassing the string boundaries, UB!" And you're right. In my answer, I skirted with danger when I said
Here,
ppoints to whatstrrchrthinks is the end of the string, so when I computep+1and try to print it using%s, if we don't know better it looks like I've indeed strayed into Undefined Behavior. In this case it's safe, of course, because we know exactly what's beyond the first\0. But if I were to writethen I'd definitely be well over the edge.