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

标签 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;
}

最佳答案

请注意,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_code,它是 char 而不是 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);

关于c - 为什么这个简单的程序会崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45147360/

相关文章:

java - 如何获取任意整数数组并返回具有相同整数但不重复的数组

c - 将数字数据存储在二进制文件和数据结构中

java - 迭代访问所有二叉树节点?

在 C 中将负 int 转换为更大的无符号 int

c++ - ASCII 到 int 到 ASCII (ATMEGA 2560)

c - 即使在处理程序中重置,SIGALRM 的信号处理程序也不起作用

java - 难倒: Detect identical sequence of integers in two integer arrays

Python:将 numpy 数组保存到 ROOT 文件

c - 标准c库是否提供链表等数据结构?

c - 如何在打开/写入功能中实现超时