gpt4 book ai didi

c++ - 打印数组字符串的方法

转载 作者:行者123 更新时间:2023-11-30 20:45:59 25 4
gpt4 key购买 nike

#include <stdio.h>

int main(){
char arr[] = "HelloWorld";

printf("%s\n", arr+3); //first line
printf("%s\n", &arr[4]); //second line
return 0;
}

谁能给我解释一下以下内容吗?

1)为什么第一行的输出是= loWorld?

2)为什么第二行的输出= oWorld?

3)为什么第二行需要放&?

最佳答案

你的数组是这样构建的

---------------------------------------------
| H | e | l | l | o | W | o | r | l | d |\0 |
---------------------------------------------
| | | |
arr arr+1 arr+3 &arr[4]

因此 %s 会打印字符串,直到遇到 \0 字符。您正在从 arr+3 打印到字符串末尾。

请注意, arr+1&arr[1] 相同,arr+2&arr[ 相同2]

&arr[4] 将给出字符串中第 5 个元素的地址(对于指针,它是 arr+4)和 %s 从那里打印字符串直到字符串末尾。

关于c++ - 打印数组字符串的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31098344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com