我正在尝试为我的大学课程实现链接列表数据结构,但在执行代码时,以下行会产生 EXC_BAD_ACCESS(code=1, address=0x8) 错误。
temp->next = (ptrtonode) malloc(sizeof(struct node));
以下是完整的代码。
#include <stdio.h>
#include <stdlib.h>
typedef struct node *ptrtonode;
typedef ptrtonode header;
struct node
{
int data;
ptrtonode next;
};
ptrtonode create(int n)
{
int i;
header temphead = NULL;
ptrtonode temp = temphead;
for(i=0;i<n;i++)
{
temp->next = (ptrtonode) malloc(sizeof(struct node));
printf("Enter data for node %d: ", i+1);
scanf("%d", &temp->next->data);
temp = temp->next;
}
temp->next = NULL;
return temphead;
}
int main(int argc, const char * argv[])
{
header head;
int n;
printf("How many nodes do you wish to create?");
scanf("%d", &n);
head = create(n);
}
任何帮助,将不胜感激。谢谢大家!