I am learning c, a beginner, can anybody please make me understood which concept am I missing? And thanks in advance.
#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;
}
Change
printf("%s", *p);
to
printf("%s", p);
The reason why is that %s
is expecting a pointer, and *p
is the dereferenced value at p
, aka the char value at p[0]
.
If this doesn't make sense, picture why printf("%c\\n", *p)
works. *p
is the same as p[0]
, which is the same as s[0]
since p
points to s
. Because s[0]
is a char
, %c
works here because it is expecting a char
. But %s
on the other hand expects char *
.
You want printf("%s", p)
. Don't dereference the pointer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.