5

为什么程序,

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);

给出以下结果?

 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'

编译器是如何继续这个序列的?为什么s[3]返回一个空值?

4

2 回答 2

9

它不会继续序列。您正在执行*s+3which first dereferencess为您char提供 with value 'a',然后您正在添加该char值。添加 3'a'给您'd'(至少在您的执行字符集中)的值。

如果您将它们更改为*(s+1)等等,您将获得预期的未定义行为。

s[3]访问字符串的最后一个元素,即空字符。

于 2013-05-11T14:54:13.217 回答
2

请注意,这*s是一个字符,本质上是一个数字。向其中添加另一个数字会产生具有更高 ASCII 值的字符。为s[3]空,因为您仅将“abc”分别分配给条目 0、1、2。事实上,第三个字符是 '\0' 字符。

于 2013-05-11T14:55:31.423 回答