在C++中递增字符指针
Incrementing char pointers in 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);
给出以下结果?
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"字符。
相关文章:
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 如何循环访问 cpp 中的函数返回的字符指针数组
- 将(N 个字节)无符号字符指针转换为浮点数和双 C++
- 字符指针的 Qt 数组
- C++将常量字符* 指针数组传递给对象
- 为什么不能将字符指针定义为数组?
- 在函数内初始化无符号字符指针将返回空指针
- 将字符指针存储到容器中
- 为什么 strtok_r() 只接受字符数组而不接受字符指针
- 字符指针数组内存分配
- 字符指针不递增?
- 如何在C++中使用字符指针
- 确保字符指针始终指向相同的字符串文字
- C++中的字符指针
- 使用unique_ptr的常量字符指针
- 字符指针不断意外更改
- 将字符指针中的十六进制转换为十进制
- 如何将字符*(字符指针)转换为 PCSZ?
- 在向量中存储字符指针
- 字符指针具有不同的值