我一直在学习C并遇到以下代码。我知道它的作用,但我不知道它为什么这样做。
char str[5] = "hele";
printf("string is %s: \n", &str[1]);
output:
ele
为什么&str[1]输出ele?从我到目前为止所读到的内容来看, & 返回地址,因此 &str[1] 不应该返回“e”的地址。由于输出是“ele”,我知道情况并非如此,但我无法弄清楚为什么。感谢所有帮助。
最佳答案
这是printf
的原型(prototype):
int printf(const char *format, ...);
它与转换说明符一起使用,例如 %d、%a、%s、%c...
如果使用 %s
,则 const char *
参数应为指向字符类型数组的指针(指向字符串的指针)。
返回您的案例:
&str[1]
确实指向 'e'
并且它是一个指向字符串的指针,因此 printf< 的参数
显然具有正确的类型。
接下来 printf 会做什么,请参阅 Cobster 的优质评论
The %s in the printf function uses it as the start of the string and will continue until it encounters a null terminator
关于c - 使用 & 与数组返回意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35592517/