【发布时间】:2015-01-05 02:28:36
【问题描述】:
我想创建一个双链表,但在访问结构中的字段时遇到问题。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int val;
struct node * next;
struct node * prev;
}node;
void insert(int val, node **head)
{
node * temp= *head;
node * temp2=(node *)malloc(sizeof(node));
node * temp3=(node *)malloc(sizeof(node));
temp2->val=val;
temp2->prev=NULL;
temp2->next=*head;
*head=temp2;
temp2->next->prev=temp2;
}
void print(node* head)
{
node* temp=head;
while(temp!=NULL)
{
printf("%d ", temp->val);
temp=temp->next;
}
}
int main()
{ node * head=NULL;
insert(1, &head);
insert(2, &head);
print(head);
return 0;
}
我在temp2->next->prev 遇到了崩溃,我不明白为什么。我是否不允许访问 temp2->next 节点的 prev 字段?我试过写(temp2->next)->prev,但也没有用。有什么方法我不能让它工作吗?
【问题讨论】:
-
如果发生崩溃,这通常意味着您尝试使用
*或->取消引用的指针要么是NULL,要么未初始化。所以检查temp2和temp2->next。
标签: c list dynamic dynamic-allocation