gpt4 book ai didi

C程序跑不起来——初学者对指针&字符的疑问

转载 作者:太空宇宙 更新时间:2023-11-04 01:02:53 25 4
gpt4 key购买 nike

我无法运行这个程序。我不断收到错误消息:

10|warning: format '%u' expects argument of type 'unsigned int', but argument 2 has type 'char *' [-Wformat]|

另一个是:

6|warning: 's1' is used uninitialized in this function [-Wuninitialized]|

int main()
{
char *s1, *s2;
*s1='p';
*s2 ='q';
printf("%d %d\n", sizeof(s1), sizeof(s2));
printf("Value of *s1 = %c \n", *s1);
printf("Address of *s1 = %u \n", s1);
printf("Address of *s2 = %u \n", s2);
return 0;
}

我是 C 语言的初学者。如果能帮助我解释这里的错误,我们将不胜感激。谢谢。

最佳答案

首先,让我告诉你,在你的代码中,

*s1='p';
*s2 ='q';

两条指令都试图写入未初始化的内存区域。它调用 undefined behaviour .

在使用它们之前,您需要为 s1s2 分配内存。也许malloc()可以提供帮助。

也就是说,

  • 使用 %zu 打印 sizeof 的输出,类型为 size_t
  • 使用%p打印一个地址,并将相应的参数转换为(void *)

关于C程序跑不起来——初学者对指针&字符的疑问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31704964/

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