用于结构的 Malloc

Malloc for structures

我在这里没有得到正确的输出, 该代码将输入的编号和选项作为输入,然后采用学生年级和性别的名称,并根据提供的选项给出输出。输出可以是字典中第一个出现的名字,也可以是输入中年份中较小的值。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct student_record
{
    int passing_year;
    char gender;
    char name[20];
};

typedef struct student_record student;

student* find_specific(student* find, int option_num, int number)
{
    int i;
    student* temp = find;
    int opt = option_num;
    int num = number;

    if(opt==1)
    {
        for(i=0; i<num; i++)
        {
            if( strcmp(temp->name, find[i].name) >0)
                temp = find+i;
        }
    }
    else
    {
        for(i=0; i<num; i++)
                {
                    if (temp->passing_year > find[i].passing_year)
                        temp = find+i;
                }
    }

    return temp;

}

int main() {

    student* example;
    student* final;

    int i;
    int option_num, number_of_students;
    printf("Enter 2the number of students, option number");
    scanf("%d" "%d", &number_of_students, &option_num);

    example = (student* )malloc(number_of_students * sizeof(student));

    printf("Enter the name, passing year and gender");
    for(i=0; i< number_of_students; i++)
    {

        scanf("%s" "%d" "%c", example[i].name, &example[i].passing_year, &example[i].gender);
    }

    final = find_specific(example, option_num, number_of_students);

    printf("%s" "%d" "%c", final->name, final->passing_year, final->gender );





    return 0;
}

我遇到了分段错误。我不知道我到底哪里搞砸了。

您的 scanf()printf() 格式字符串可能有误。

scanf("%s" "%d" "%c", example[i].name, &example[i].passing_year, &example[i].gender);

应该是

scanf("%s %d %c", example[i].name, &example[i].passing_year, &example[i].gender);

(没有额外的引号)。编译器将连接相邻的 字符串文字,因此它没有编译器错误,而是将您的格式字符串解释为等同于 "%s%d%c" (中间没有空格)。 这可能与您输入的布局不匹配,因此某些值可能未初始化,从而导致以后出现问题。

您应该始终检查 scanf 和类似库函数的 return 值, 以确保您获得了您告诉编译器期望的输入格式。