Printing next string in array of pointers to strings( char *arr[ ] ) in C -
why code doesn't print parasyte ? , how printing string works when use %s pointer of first char! , shouldn't give me error ?
#include <stdio.h> int main () { char *anime[] = { "naruto", "parasyte" }; printf ("anime %s \n", anime[0] + 7); return 0; }
edit: anime[0] + 7
undefined behavior because can't assure inside memory strings going adjacent. using anime[1]
indeed right solution problem. see below comments of answer explanation.
because anime[0] + 6
points null-terminator instead of next string.
internally, anime
array stored in memory:
n, a, r, u, t, o, \0, p, a, r, a, s, y, t, e, \0
so can see, there "invisible" null-terminator @ end of "naruto"
string.
a workaround might add 7
instead of 6
, point next string.
#include <stdio.h> int main () { char *anime[] = { "naruto", "parasyte" }; printf ("anime %s \n", anime[0] + 7); return 0; }
or else using anime[1]
instead, way cleaner.
Comments
Post a Comment