我爱学习来
2019-05-31 00:19
采纳率: 100%
浏览 883

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条回答 默认 最新

  • ma_xudong 2019-05-31 11:32
    已采纳

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

    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题