我正试图在C中制作一个链表,它可以接受字符串作为数据。我已经实现了push、free和pop函数,但我的问题是,在pop函数中,当我尝试释放它时,它无法识别名称作为成员。
typedef struct list
{
char* name;
struct list* next;
} node;
void free_list(node*head)
{
if(head==NULL){
return;
}
node* temp=NULL;
while (head!= NULL)
{
temp=head->next;
free(head->name);
free(head);
head=temp;
}
head=NULL;
}
/*add elements to the front of the list*/
void push_list(node **head, char* name)
{
node *temp=malloc(sizeof(node));
if(temp==NULL)
{
fprintf(stderr,"Memory allocation failed!");
exit(EXIT_FAILURE);
}
temp->name=strdup(name);
temp->next=*head;
*head=temp;
}
void pop_list(node ** head) {
node * next_node = NULL;
if (*head == NULL) {
return;
}
next_node = (*head)->next;
free(*head->name); //this line generating error
free(*head);
*head = next_node;
}
bool empty_list(node *head){
return head==NULL;
}
我猜测这可能与我的指针使用不当有关?有点困难。
main
函数也包含进来吗? - Robert Lacherfree((*head)->name);
? - aschepler