在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(...),我无法改变。此函数创建一个新学生并将其存储在列表中的适当位置(按字典顺序)。这就是我到目前为止...... 我的问题:我不知道如何访问enum 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;
}
答案 0 :(得分:0)
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