3
我试图为我的大学课程实现链表数据结构,但是在执行代码时,以下行会产生EXC_BAD_ACCESS(code = 1,address = 0x8)错误。malloc()在Xcode中导致EXC_BAD_ACCESS错误
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);
}
任何帮助,将不胜感激。 谢谢大家!
如果'temphead'不是'NULL',然后在'temp = temphead'赋值,Xcode吐出一个警告:_Variable'temphead'在这里使用时未初始化,程序停在'malloc()'行。说'线程1:断点1.1' 我不明白。这似乎在大学的Fedora中起作用。我现在做错了什么? 哦,我也实现了你的其他观点。 – vigneshwerv
没关系,我在分配'temp = temphead'之前将内存分配给'temphead'。该程序现在工作得很好。谢谢。 – vigneshwerv