如何链接带有指针的两个结构?

问题描述

在C语言中此问题需要指针,但是我无法理解如何与指针链接课程和学生结构。程序应执行AddCourse操作并获取课程ID和学生ID,如果我写出口,则再次再次循环添加课程,停止循环打印学生所学课程和结构信息。这是问题:

结构必须由用户输入填充。填充结构后,您 将允许用户从课程列表中让任何学生注册任何课程。提示:实现 这些步骤,您必须在学生结构中使用指针将其链接到课程结构”

我为期望的程序输出添加照片 打开,这两个图像和两个图像是相关的。

1.photo

2.photo

及其我不完整的代码,因为我该如何使用指针来链接两个结构。

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

struct student
{
    char name[50],surname[50];
    int  id,year;
};

struct Courses{
    char course_name[50];
    int course_id,course_credit;
};

int main(){
    struct student std[2];
    struct Courses crs[4];
    
    printf("enter information of students:\n");
    for(int i=0; i<2;i++){
        printf("Enter student id:");
        scanf("%d",&std[i].id);
        printf("Enter first name:");
        scanf("%s",std[i].name);
        printf("Enter last name:");
        scanf("%s",std[i].surname);
        printf("Enter year:");
        scanf("%d",&std[i].year);
        printf("\n");
    }
    printf("Enter information of courses:\n");
    for (int i = 0; i < 4; i++)
    {
        printf("course id:");
        scanf("%d",&crs[i].course_id);
        printf("course name:");
        scanf("%s",&crs[i].course_name);
        printf("course credit:");
        scanf("%d",&crs[i].course_credit);
        printf("\n");
    }
    printf("-displaying Courses-\n");
    for(int i=0; i<4;i++){
        printf("course id:%d\n",crs[i].course_id);
        printf("course name :%s\n",crs[i].course_name);
        printf("course credit:%d",crs[i].course_credit);
        printf("\n");
    }
    printf("-display Students-\n");
    for(int i=0; i<2;i++){
        printf("student id:%d\n",std[i].id);
        printf("student name and surname:%s %s\n",std[i].name,std[i].surname);
        printf("year:%d",std[i].year);
        printf("\n");
    }
    return 0;
}

解决方法

您需要第三个数据结构来链接学生和课程。

如@tadman所述,链表是一种可用于此目的的数据结构。有关实现的一种版本,请参见How to implement a linked list in C?

此外,https://en.wikipedia.org/wiki/Data_structure列出了一些其他常用的。您应该选择哪种类型取决于您的要求(例如,排序,插入/删除等)。

除了您的问题外,以下是一些简短(非详尽的)清单,供您根据发布的代码来考虑:

  1. 除了数组之外,对“ std”和“ crs”使用其他数据结构。在此数据结构中,您可以使用帮助程序函数来封装当前主函数中的许多行(例如printCourses())

  2. 使用scanf函数可能会导致意外和不确定的行为。参见Disadvantages of scanfHow to read / parse input in C? The FAQ

  3. 而不是对数组大小进行硬编码(例如,名称[50]),请使用#define MAX_NAME_LENGTH 50和名称[MAX_NAME_LENGTH]