我定义了这些结构:
typedef struct {
char *first_name;
char *last_name;
char SSN[9];
float gpa;
struct student *next;
} student;
typedef struct {
student *head;
student *current;
student *tail;
} students;
在我的主要功能中,我想在学生结构中添加一名学生。然后,调用头部学生的first_name。我该怎么做?
void add(students *list, student *a) {
if(list->head) {
a->next = NULL;
list->head = &a;
list->current = list->head;
list->tail = NULL;
} else {
printf("Will implement");
}
}
int main()
{
students grade1;
student a;
a.first_name = &"Misc";
a.last_name = &"Help";
add(&grade1, &a);
printf("%s %s", a.first_name, a.last_name);
printf("%s", grade1.head->first_name);
}
printf("%s",grade1.head-> first_name);
似乎不起作用。有什么建议吗?
由于
答案 0 :(得分:0)
首先,您必须初始化对象grade1
的所有数据成员。例如
students grade1 = { 0 };
其次而不是
student a;
a.first_name = &"Misc";
a.last_name = &"Help";
至少应该有
student *a = malloc( sizeof( student ) );
a->first_name = "Misc";
a->last_name = "Help";
a->next = NULL;
功能add
可能看起来像
void add( students *list, student *a )
{
if ( list->tail == NULL )
{
list->head = list->tail = a;
}
else
{
list->tail->next = a;
}
}
它可以被称为
add( &grade1, a );