2014-09-11 97 views
-2

我有这些结构定义:C程序调用指针的指针

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; 

在我的主要功能,我想在同学结构添加学生。然后,打电话给首席学生的名字。我怎么做?

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);

似乎没有工作。有什么建议么?

感谢

+2

'似乎没有工作。'什么不工作?你想要什么?这段代码是否编译?具体关于你的问题。 – 2014-09-11 04:20:48

+1

你是不是收到关于'list-> head =&a;'上的不正确类型的警告?如果新学生被列入名单的头部,你是否需要将一些东西放在列表的旧头上,以免失去它? – Barmar 2014-09-11 04:29:05

+0

我想要grade1.head-> first_name返回杂项 – Raza 2014-09-11 04:36:50

回答

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

而且它可以被称为as

add(&grade1, a);