【问题标题】:Codeblocks crashes after inputting a character while some other code is also executed输入字符后代码块崩溃,而其他一些代码也被执行
【发布时间】:2018-09-25 05:49:44
【问题描述】:

我是新手,如果这是一个已经回答的常见问题,请原谅我。

problem here

works fine

因此,如果我不在结构中输入任何数据,基本上我的代码可以正常工作,但如果我在结构中输入数据,它会在输入一些甚至不是结构的一部分的随机字符后崩溃。 下面的代码-

#include<stdio.h>
#include<math.h>
#include<string.h>
struct student
{
    char name[50];
    int roll;
    float marks;
};
main()
{
    int n,i;
    char a;
    printf("Enter the number of entries (students): ");
    scanf("%d",&n);
    for(i=1;i<=n;i++){
        struct student s[i];
        printf("\n\nEnter the name of student %d: ",i);
        scanf("%s",s[i].name);
        printf("Enter the roll number of %s: ",s[i].name);
        scanf("%d",&s[i].roll);
        printf("Enter the marks of %s: ",s[i].name);
        scanf("%f",&s[i].marks);
    }

    printf("Now enter any character: ");
    scanf(" %c", &a);
    printf("\n\n%c",a);      //CRASHES AFTER HERE

}

【问题讨论】:

  • 您在循环中使用数组没有意义。
  • 另外,崩溃的不是IDE,而是你的程序。而且您通常使用 调试器 来捕捉发生的崩溃。
  • 最后一个关于实际问题的提示:对于i元素的数组,索引的有效范围是多少?请记住,索引是基于的。
  • 感谢帮助,问题解决了。

标签: c struct crash scanf codeblocks


【解决方案1】:

所以我应该将结构变量声明为

struct student s[n];

在循环之外,当然必须从零开始索引(和循环)(到小于 n)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-30
    • 2015-09-16
    • 2017-10-22
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多