【发布时间】:2016-05-18 21:46:57
【问题描述】:
您好,我是编程新手。
在下面的代码中str 是一个指向字符的指针,所以str 应该包含字符'h' 的地址。因此应使用 %p 打印该地址。但我不明白 %s 是如何用于打印指针参数的。
#include<stdio.h>
int main (){
char s[] = "hello";
char *str = s;
int a[] = {1, 2, 3, 4, 5};
int *b = a;
printf("%s\n", str); // I don't understand how this works ?
printf("%c\n", *str); // This statement makes sense
printf("%c\n", *(str + 1)); // This statement also makes sense.
printf("%p\n",str); // This prints the address of the pointer str. This too makes sense.
printf("%d\n",*b); // makes sense, is the same as the second print.
// printf("%d",b); // I don't understand why str pointer works but this gives a compile error
return 0;
}
【问题讨论】:
-
什么不清楚?为什么字符串格式说明符适用于字符串?因为它被定义为工作......
-
我无法理解第一次打印。我认为如果第一次打印有效,评论中的最后一次打印也应该有效,但那不是真的,所以这就是我的问题,谢谢。
-
为什么
printf("%d", b);不应该给出错误? -
@user6353278 你到底有什么不明白的?
str是一个数组hello怎么会被打印出来? -
%s表示:检索char*参数。取消引用指针并打印字符和后续字符,直到遇到\0。
标签: c arrays string pointers character