输入字符后代码块崩溃,同时还执行其他一些代码

时间:2018-04-15 11:05:24

标签: c struct crash scanf codeblocks

如果这是一个已经回答的常见问题,我就是新手了

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

}

1 个答案:

答案 0 :(得分:0)

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

struct student s[n];
循环之外的

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