gpt4 book ai didi

c - 为什么程序会因使用 '%s' 取消引用 char 指针而崩溃?

转载 作者:太空宇宙 更新时间:2023-11-04 06:18:06 24 4
gpt4 key购买 nike

我正在学习 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 需要一个指针,而 *pp 处的解引用值,也就是 char 值在 p[0]

如果这没有意义,想象一下为什么 printf("%c\n", *p) 有效。 *pp[0]相同,因为ps[0]相同指向 s。因为 s[0] 是一个 char%c 在这里工作是因为它需要一个 char。但另一方面,%s 需要 char *

关于c - 为什么程序会因使用 '%s' 取消引用 char 指针而崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41107212/

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