c - 用于结构的 Malloc

标签 c struct malloc

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

#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 和类似库函数的返回值, 以确保您获得了您告诉编译器期望的输入格式。

关于c - 用于结构的 Malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28533462/

相关文章:

c - C 编程中的结构(初始化语句)

c++ - GLib HashTable 将函数作为参数传递

java - 国际象棋引擎是c还是java,性能有区别吗?

c - 使用结构字段作为循环计数器?

c - 我是否以错误的方式使用结构?

c - c中的指针和动态内存分配

将 C#define 常量转换为变量

c - 如何在 C 中的结构中初始化结构?

c - C中的字符串操作

c - 如何在C中使用malloc正确分配内存