3

我正在尝试为我的大学课程实现链接列表数据结构,但在执行代码时,以下行会产生 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);
}

任何帮助,将不胜感激。谢谢大家!

4

1 回答 1

2

在函数for内部的循环的第一次迭代中,它被取消引用,导致失败(不导致失败)。您将需要稍微重构代码以防止取消引用指针。create()tempNULLmalloc()NULL

其他要点:

  • malloc()不需要转换返回值。
  • 检查结果scanf()以确保n分配了一个有效的整数(并确认int是正数):

    /* scanf() returns the number of assignments made,
       which in this case should be 1. */
    if (1 == scanf("%d", &n) && n > 0)
    {
        /* 'n' assigned a sensible value. */
    }
    
于 2012-11-08T10:14:29.000 回答