【问题标题】:How can i link two struct with pointers?如何用指针链接两个结构?
【发布时间】:2021-02-02 07:58:21
【问题描述】:

在 c 语言中,这个问题需要指针,但是我无法理解如何使用指针链接课程和学生结构。程序预期的 AddCourse 操作并获取课程 ID 和学生 ID,如果我写退出,则再次再次循环 addcourse循环和打印学生参加的课程和结构信息。这就是问题:

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

我为预期的程序输出添加照片 打开这两个图像和两个图像依赖。

这是我不完整的代码,因为我如何使用指针链接两个结构。

#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;
}

【问题讨论】:

  • 最简单的方法是某种链表结构,您可以将student链接起来。
  • 提示:尽量保持你的大小写约定一致。看到小写的student 和大写的Courses 很奇怪。 “Courses”(复数)代表一门课程,这也很奇怪。

标签: c loops pointers struct


【解决方案1】:

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

正如@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. 不要硬编码数组大小(例如 name[50]),而是使用 #define MAX_NAME_LENGTH 50 和 name[MAX_NAME_LENGTH] 之类的东西

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    相关资源
    最近更新 更多