VS2017中使用strcpy_s时引发异常,代码如下,求教时什么原因?

#include
#include
#include
typedef struct student
{
char name[10];
char number[10];
int score;
}student;
int main()
{
int i, c, m, flag, j;
struct student stu[3];
strcpy_s(stu[0].number , "00007");
stu[0].score = 85;
strcpy_s(stu[0].name, "James");
strcpy_s(stu[1].number , "00010");
stu[1].score = 90;
strcpy_s(stu[1].name, "Amy");
strcpy_s(stu[2].number , "00001");
stu[2].score = 60;
strcpy_s(stu[2].name, "Zoe");
printf("初始顺序为:\n");
for (i = 0;i < 3;i++)
{
printf("%s %s %d\n", stu[i].name, stu[i].number, stu[i].score);
}
scanf_s("%d", &c);
if (c==0)
{
m = 2;flag = 1;
while ((m > 0) && (flag == 1))
{
flag = 0;
for (j = 0;j {
if (strcmp(stu[j].name, stu[j + 1].name)>0)
{
stu[3].score = stu[j].score;
strcpy_s(stu[3].name, stu[j].name);
strcpy_s(stu[3].number,stu[j].number);//此处出错
stu[j].score = stu[j+1].score;
strcpy_s(stu[j].name, stu[j+1].name);
strcpy_s(stu[j].number, stu[j+1].number);
stu[j+1].score = stu[3].score;
strcpy_s(stu[j+1].name, stu[3].name);
strcpy_s(stu[j+1].number, stu[3].number);
flag = 1;
j++;
}
else
{
j++;
}
}
m--;
}
printf("排序后数据:\n");
for (i = 0;i < 3;i++)
{
printf("%s %s %d\n", stu[i].name, stu[i].number, stu[i].score);
}
}
if (c == 1)
{
m = 2;flag = 1;
while ((m > 0) && (flag == 1))
{
flag = 0;
for (j = 0;j < m;j++)
{
if (strcmp(stu[j].number ,stu[j+1].number )>0 )
{
stu[3].score = stu[j].score;
strcpy_s(stu[3].name, stu[j].name);
strcpy_s(stu[3].number, stu[j].number);
stu[j].score = stu[j + 1].score;
strcpy_s(stu[j].name, stu[j + 1].name);
strcpy_s(stu[j].number, stu[j + 1].number);
stu[j + 1].score = stu[3].score;
strcpy_s(stu[j + 1].name, stu[3].name);
strcpy_s(stu[j + 1].number, stu[3].number);
flag = 1;
j++;
}
else j++;
}
m--;
}
printf("排序后数据:\n");
for (i = 0;i < 3;i++)
{
printf("%s %s %d\n", stu[i].name, stu[i].number, stu[i].score);
}
}
if (c == 2)
{
m = 2;flag = 1;
while ((m > 0) && (flag == 1))
{
flag = 0;
for (j = 0;j < m;j++)
{
if (stu[j].score > stu[j + 1].score )
{
stu[3].score = stu[j].score;
strcpy_s(stu[3].name, stu[j].name);
strcpy_s(stu[3].number, stu[j].number);
stu[j].score = stu[j + 1].score;
strcpy_s(stu[j].name, stu[j + 1].name);
strcpy_s(stu[j].number, stu[j + 1].number);
stu[j + 1].score = stu[3].score;
strcpy_s(stu[j + 1].name, stu[3].name);
strcpy_s(stu[j + 1].number, stu[3].number);
flag = 1;
j++;
}
else j++;
}
m--;
}
printf("排序后数据:\n");
for (i = 0;i < 3;i++)
{
printf("%s %s %d\n", stu[i].name, stu[i].number, stu[i].score);
}
}
system("pause");
return 0;
}

3个回答

首先你定义结构体数组的时候开了3个空间,下标st[3]是取不到的,数组下标从0开始,你这就已经越界了,虽然说strpy_s传2个还是3个参数都可以,但一般传3个参数好一点,传2个参数的时候要求有点特殊,你可以百度一下,这里应该是由于你越界操作数组,空间是新开的,恰好导致不满足strcpy_s传两个参数的要求(要求可能是传的第一个参数的空间够,而且大小也要一定QAQ),望采纳

Studddy
我爱学习来 谢谢!明白了!
一年多之前 回复

strcpy_s(stu[0].number , "00007");
->
strcpy_s(stu[0].number, 10 , "00007");
别的类似

strcpy_s括号里面应该应该有三个参量吧,你的貌似没有第三个复制字符数目的数?

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问