[英]Simple C code keeps crashing
So this is the code i did:所以这是我做的代码:
#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;
}
And everytime i run it, after i input my name it crashes and i don't know how to fix it.每次我运行它时,在我输入我的名字后它就会崩溃,我不知道如何修复它。 These 3 things appear when it closes:关闭时会出现以下 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]|
What is my mistake?我的错误是什么?
scanf("%s\\n", playerName);
is wrong because %s
call for char*
data but playerName
here is type char
.是错误的,因为%s
调用char*
数据,但playerName
是char
类型。
You have to make playerName
an array of characters and set max length of input to avoid buffer overflow.您必须将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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.