在parser.h中:
typedef enum _SEX {MALE = 'M', FEMALE = 'F', OTHER = 'O'} SEX;
struct course {
char grade;
unsigned int number;
struct course *next;
};
struct student {
char name[MAX_NAME_LEN];
unsigned int age;
SEX sex;
float gpa;
struct course *courses;
struct student *next;
};
在parser.c中: 我有一个函数 struct Student * enroll_student(...) 我无法更改。此函数创建一个新学生并将其存储在列表中适当的位置(遵循字典顺序)。这就是我到目前为止所拥有的...... 我的问题:我不知道如何访问枚举 SEX,也不知道这是否是正确的方法。 任何反馈或帮助将不胜感激。谢谢你!
/*globally declared*/
static struct student *head;
struct student* enroll_student(char *name, unsigned int age, SEX sex, float gpa){
struct student *enroll = NULL;
/*allocate memory*/
enroll = (struct student*)malloc(sizeof(struct));
if(enroll != NULL){
/*INITIALIZE*/
strncpy(enroll->name, name, MAX_NAME_LEN);
enroll->age = age;
/* How do I access the ENUM SEX?*/
enroll->gpa = gpa;
enroll->next = NULL;
}
return enroll;
}
最佳答案
enroll_student
函数不用于在链接列表中插入任何内容。该函数的目的是 a) 创建一个新的学生对象并 b) 初始化该对象。因此,当您想要一个新的学生对象时,您可以调用该函数,但必须在该函数外部添加用于在链接列表中插入学生对象的代码。像这样的东西:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 100
typedef enum _SEX {MALE = 'M', FEMALE = 'F', OTHER = 'O'} SEX;
struct course {
char grade;
unsigned int number;
struct course *next;
};
struct student {
char name[MAX_NAME_LEN];
unsigned int age;
SEX sex;
float gpa;
struct course *courses;
struct student *next;
};
struct student* enroll_student(char *name, unsigned int age, SEX sex, float gpa){
struct student *enroll = NULL;
/*allocate memory*/
enroll = malloc(sizeof *enroll);
if(enroll != NULL){
/*INITIALIZE*/
strncpy(enroll->name, name, MAX_NAME_LEN);
enroll->age = age;
enroll->sex = sex;
enroll->gpa = gpa;
enroll->courses = NULL;
enroll->next = NULL;
}
return enroll;
}
int main(void) {
static struct student *head = NULL;
struct student* st;
// Make a new student
st = enroll_student("Bart", 21, MALE, 1.0);
// Insert in front of list
st->next = head;
head = st;
// Make a new student
st = enroll_student("Kim", 25, FEMALE, 1.0);
// Insert in front of list
st->next = head;
head = st;
// Print all students in the list
struct student* tmp = head;
while (tmp)
{
printf("Name: %s\n", tmp->name);
tmp = tmp->next;
}
// Free allocated memory
while (head)
{
tmp = head;
head = head->next;
free(tmp);
}
return 0;
}
输出:
Name: Kim
Name: Bart
关于创建一个链表来注册 C 学生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46937790/