gpt4 book ai didi

c - 简单的 C 代码总是崩溃

转载 作者:行者123 更新时间:2023-11-30 21:43:45 24 4
gpt4 key购买 nike

这就是我所做的代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
char playerName;
int playerAge;

printf("What's your name, and your age?\nYour name: ");
scanf("%s\n", playerName);
printf("Your age: ");
scanf("%d\n", &playerAge);
printf("Okay %s, you are %d years old!", playerName, playerAge);

return 0;
}

每次我运行它时,输入我的名字后它都会崩溃,我不知道如何修复它。关闭时会出现以下 3 件事:

format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat]|

format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat]|

'playerName' is used uninitialized in this function [-Wuninitialized]|

我的错误是什么?

最佳答案

scanf("%s\n", playerName); 错误,因为 %s 调用 char* 数据,但 这里的playerName是类型char

您必须将 playerName 设置为字符数组并设置输入的最大长度以避免缓冲区溢出。

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
char playerName[1024];
int playerAge;

printf("What's your name, and your age?\nYour name: ");
scanf("%1023s\n", playerName); /* max length = # of elements - 1 for terminating null character */
printf("Your age: ");
scanf("%d\n", &playerAge);
printf("Okay %s, you are %d years old!", playerName, playerAge);

return 0;
}

关于c - 简单的 C 代码总是崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33462268/

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