为什么这个简单的程序会崩溃?

时间:2017-07-17 14:50:44

标签: c arrays data-structures

我基本上有一个结构,里面有学生的信息。在最后一次输入后,它崩溃了。永远不会显示最后一个printf,我的编译器没有发现任何错误。

struct stud_prof {
    char student_name[NAME_LIMIT];
    char ssn_number[SSN_LIMIT];
    double gpa;
    int units;
    char major_code;
} student1;



int main(void)
{
    printf( "What is the student's name?\n" );
    scanf(" %s", &student1.student_name);

    fflush(stdin);

    printf( "What is the student's Social Security number?\n" );
    scanf(" %s", &student1.ssn_number);

    fflush(stdin);

    printf( "What is the student's GPA?\n" );
    scanf(" %lf", &student1.gpa);

    fflush(stdin);

    printf( "How many units has the student completed?\n" );
    scanf(" %d", &student1.units);

    fflush(stdin);

    printf( "Enter the student's Major Code.\n" );
    scanf( " %s", &student1.major_code);

    printf( " %s, %s, %f, %d, %s ", student1.student_name, 
    student1.ssn_number, student1.gpa, student1.units, student1.major_code);




    return 0;
}

1 个答案:

答案 0 :(得分:3)

请注意fflush(stdin);是未定义的行为,但这很可能不是导致此问题的原因。

这是错误的:

printf( "Enter the student's Major Code.\n" );
scanf( " %s", &student1.major_code);

printf( " %s, %s, %f, %d, %s ", student1.student_name, 
student1.ssn_number, student1.gpa, student1.units, student1.major_code);

格式说明符与参数不匹配。

%s使用的student1.major_codechar而不是char*。 请改用%c

printf( "Enter the student's Major Code.\n" );
scanf( " %c", &student1.major_code);

printf( " %s, %s, %f, %d, %c", student1.student_name, 
student1.ssn_number, student1.gpa, student1.units, student1.major_code);