在C++中递增字符指针

Incrementing char pointers in C++

本文关键字:字符 指针 C++      更新时间:2023-10-16

为什么程序,

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+3,它首先取消引用s,为您提供值为'a'char,然后添加到char的值上。将3添加到'a'会得到'd'的值(至少在执行字符集中(。

如果您将它们更改为*(s+1),依此类推,您将得到预期的未定义行为。

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

请注意,*s是一个字符,本质上是一个数字。在其中添加另一个数字,会生成一个ASCII值更高的字符。s[3]为空,因为您只将"abc"分别分配给条目0,1,2。事实上,第三个字符是"\0"字符。