C-程序停止工作,并且在我运行时会显示错误消息



此错误消息在每个软件中显示。

它已经停止工作检查在线解决方案并关闭程序

代码中没有错误,但是当我运行此程序时,我会收到此错误,我发现需要用户输入的大多数程序都停止工作。我使用了代码块,c free,dev c

#include<stdio.h>
#include<conio.h>
struct student
{
    int roll;
    char name[10];
} stu1 = {100, "ram"};
main()
{
    struct student stu2;
    printf("2nd student name is:  %s n",stu1.name);
    printf("second student roll no:  %s n ",stu1.roll);
    printf("enter second student data  ");
    scanf("%d", &stu2.roll);
    printf("enter second student name  ");
    scanf("%s",&stu2.name);
    printf("2nd student name is:  %s n",stu2.name);
    printf("second student roll no:  %s n ",stu2.roll);
    getch();
}

带有错误消息的图像:https://i.stack.imgur.com/zzsau.png

#include<stdio.h>
struct student
{
    int roll;
    char name[10];
}stu1 = {100, "ram"};

int main()
{
    struct student stu2;
    printf("2nd student name is:  %s n",stu1.name);
    printf("second student roll no:  %d n ",stu1.roll); // line 1
    printf("enter second student data  ");
    scanf("%d", &stu2.roll);
    printf("enter second student name  ");
    scanf("%s",stu2.name); // line 2
    printf("2nd student name is:  %s n",stu2.name);
    printf("second student roll no:  %d n ",stu2.roll); // line 3
    return 0;
}

我已经纠正了这样的代码。我认为第1、2和3行是问题。如上图所示,更改这些行时,代码不再运行到细分故障。

nb:不要将scanf用于用户输入。如果您完全使用scanf,请始终检查其返回值。scanf %s是一个错误:它无法阻止缓冲区溢出更长的输入。

这可能是另一种方法:

#include<stdio.h>
#include<conio.h>
typedef struct
{
    int roll;
    char *name;
} studentT;
int main()
{
    studentT stu1, stu2;
    stu1.roll = 100;
    stu1.name = "ram";
    printf("2nd student name is:  %s n",stu1.name);
    printf("second student roll no:  %d n ",stu1.roll);
    printf("enter second student data  ");
    scanf("%d", &stu2.roll);
    printf("enter second student name  ");
    scanf("%s",&stu2.name);
    printf("2nd student name is:  %s n",stu2.name);
    printf("second student roll no:  %d n ",stu2.roll);
    getch();
}

相关内容

  • 没有找到相关文章