c - C 中的链表和结构 - 在函数中将链表和结构作为参数传递(C)

标签 c function struct linked-list parameter-passing

我有以下代码,我正在努力使其更具动态性和可重用性。 好吧,我有一个名为 Student 的结构和一个结构列表,其中包含所有添加的学生。我有一个函数“int addStudent(Student b, list StudentList){”,我试图将结构 Student 和 StudentList 作为参数传递。但问题是我做错了什么,我的列表不包含所有添加的学生。它只包含最后一个。 你能帮帮我吗?

注意:我必须为 "int addStudent(Student b, list StudentList)" 创建主体。不允许更改此函数的声明 ...这对我来说非常困难,我需要建议来处理...

提前致谢!

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

#define MAXSTRING 100
#define MAXLessonS 100

typedef  enum genders{
    female, 
    male
} genders;

typedef struct Student
{
    char name[MAXSTRING];
    char Surname[MAXSTRING];
    enum genders gender;
    int id;
    char Lessons[MAXLessonS][MAXSTRING];
} Student;


typedef struct list 
{
    struct list * next;
    struct Student * Student;
} list;

void printlist(list * StudentList) 
{
    list * current = StudentList;
    while (current != NULL) {
        printf("Student ID      = %d\n", current->Student->id);
        printf("Student name    = %s\n", current->Student->name);
        printf("Student Surname = %s\n", current->Student->Surname);
        printf("Student gender  = %d\n", current->Student->gender);
        printf("Student Lesson  = %s\n", current->Student->Lessons);     
        current = current->next;
    }
}


int main()
{
    Student b={"name 1","Surname 1",male,22,{"Lesson 1"}};  
    Student c={"name 2","Surname 2",female,32,{"Lesson 2"}};  

    list* StudentList = NULL;
    StudentList = malloc(sizeof(list));
    StudentList->next = NULL;
    //StudentList->next->next = NULL;

    int x=addStudent(b,StudentList);
    StudentList->next=NULL;
    int xx=addStudent(c,StudentList);

    printlist(StudentList);
    return 0;
}

int addStudent(Student b, list StudentList){
    //StudentList=malloc(sizeof(list));
    StudentList.Student = &b;
    //StudentList.next->next=NULL; 
    //free(StudentList);
    return 1;
}

最佳答案

addStudent 方法总是覆盖以前的节点。所以你的列表只包含 1 个节点。此外,要“存储”链接列表,您可能希望保留指向列表头部(第一个元素)的指针。

关于c - C 中的链表和结构 - 在函数中将链表和结构作为参数传递(C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44286735/

相关文章:

javascript - 这是 Javascript 中将对象实例设置为函数参数的最佳方式

c - 在 C 中作为函数参数的函数

c - 限制运行的线程

C# 类与结构

python - 如何在 Python 中将 256 位大端整数转换为小端?

c - 在后台运行线程并使用 OpenMP 继续 main

c - 显示 C 代码图形表示的工具

c - C 中的全局数组声明?

C、如何使用pthread_create函数创建线程

go - 同一结构中的多个互斥体?