Dlaczego program,Zwiększanie char wskaźniki w C++
char *s, *p, c;
s = "abc";
printf(" Element 1 pointed to by S is '%c'\n", *s);
printf(" Element 2 pointed to by S is '%c'\n", *s+1);
printf(" Element 3 pointed to by S is '%c'\n", *s+2);
printf(" Element 4 pointed to by S is '%c'\n", *s+3);
printf(" Element 5 pointed to by S is '%c'\n", s[3]);
printf(" Element 4 pointed to by S is '%c'\n", *s+4);
dają następujące wyniki?
Element 1 pointed to by S is 'a'
Element 2 pointed to by S is 'b'
Element 3 pointed to by S is 'c'
Element 4 pointed to by S is 'd'
Element 5 pointed to by S is ' '
Element 4 pointed to by S is 'e'
W jaki sposób kompilator kontynuował sekwencję? I dlaczego s[3]
zwraca pustą wartość?
Pierwszeństwo. Chcesz '* (s + 1)' itd. Ale '* (s + 4)' byłoby niezdefiniowanym zachowaniem. –
's [3]' zwraca 4-ci znak (są one indeksowane od 0), który jest łańcuchem kończącym znak "\ 0". –
's [3]' jest '\ 0', więc nie pokazuje żadnego –