【发布时间】:2013-05-06 02:08:40
【问题描述】:
为什么要程序,
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] 返回一个空值?
【问题讨论】:
-
优先级。你想要
*(s+1)等。但*(s+4)将是未定义的行为。 -
s[3]返回第 4 个字符(它们从 0 开始索引),它是一个以\0字符结尾的字符串。 -
s[3]是\0,所以没有显示 -
我对 Element 5 的输出持怀疑态度 - 引号之间不应有空格。
-
顺便说一句,如果您使用 C++ 而不是纯 C 进行编码,请不要使用
printf。std::cout(来自头文件<iostream>)更安全、更易于使用且不易出错。