[英]Why does program crash for dereferencing pointer to char by using '%s'?
我正在学习c,是初学者,有人可以让我理解我缺少哪个概念吗? 并预先感谢。
#include<stdio.h>
int main()
{
char s[10];
s[0]='A';
s[1]='B';
s[2]='\0';
char *p;
int i;
p=s;
printf("%c\n", *p); //It's ok.
printf("%s", *p); // or *s...what's wrong here,why does program crash?
return 0;
}
更改
printf("%s", *p);
至
printf("%s", p);
之所以是%s
期待一个指针,和*p
是在解除引用值p
,又名char值在p[0]
如果这没有意义,请说明为什么printf("%c\\n", *p)
有效。 *p
与p[0]
相同,与s[0]
相同,因为p
指向s
。 因为s[0]
是一个char
,所以%c
在这里工作是因为它需要一个char
。 但另一方面, %s
期望使用char *
。
您需要printf("%s", p)
。 不要取消引用指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.