EDIT: This is the error I am getting. 程序完美运行后,我收到此错误,我不知道原因。我试图将字符串添加到临时变量中,然后将它们添加到结构数组中,名称临时值空间为15,然后检查名称是否超过15个字符并要求用户重新输入字符串(如果为true)。这可能是因为输入名称为var的缓冲区,但我不知道。
typedef struct {
char name[15];
int score;
int riskF;
} player_info;
int main()
{
player_info players[20];
char name[15];
int gameN = 0;
int riskF = 0;
int accScore = 0;
int totalplayers = 0;
int count = 1;
int length = 0;
int maxName = 15;
printf_s("Enter player %d: ", count);
scanf_s("%s", name, 999);
length = strlen(name);
if (length < maxName)
{
strcpy_s(players[totalplayers].name, name);
totalplayers++;
count++;
}
else
{
printf_s("\nName too big; please enter a name within 15 characters!\n\n");
}
length = 0;
printf_s("done!");
return 0;
}
答案 0 :(得分:0)
至少有两个问题显而易见。第一个应该阻止成功编译,下一个更糟糕。
1)strcpy_s的参数太少,其原型显示为:
errno_t strcpy_s(char *strDest, size_t numElements, const char *strSource);
你的陈述......
strcpy_s(players[totalplayers].name, name);
...似乎缺少中间参数size_t numberOfElements,
因为这不是strcpy_s
中的可选参数,所以您显示的代码不应该编译。
2)您的代码正在调用 undefined behaviour 。您已将scanf_s函数配置为比变量name
可以容纳的内容多。除了代码中的这一点之外,没有人知道代码的行为方式。它可能会工作一次,或一百次,然后不能工作。
char name[15];
....
int maxName = 15;
scanf_s("%s", name, 999);//name can contain only 14 characters and a NULL.
^^^ //you are allowing scanf_s to read more than that.
将scanf_s
的第3个参数设置为与您要写入的char数组的size-1相匹配:
int maxName = 14;//and for same reason, change maxName
scanf_s("%s", name, 14);//room for NULL
/// or a width specifier can be used
scanf_s("%14s", name, 15);
/// BEST of all, use a portable version: scanf with width specifier
scanf(("%14s", name); //provided similar protection.
//note: scanf has not be deprecated by anyone
//except Microsoft
无论哪种方式,如果scanf_s
要防止缓冲区溢出,则必须正确设置参数。
关于你的评论:之前我制作了999缓冲区15,但是如果有超过15个字符的输入则会破坏我的代码。
您需要为NULL终止符留出空间。 ( see this C string definition )
如果填充缓冲区,大小只包含15个char
和15 char
个输入,则该数组没有空间用于NULL终止符。因此,char
数组不是C字符串,并且不能保证表现为字符串。 (UB)。