0

我收到以下错误: 0xC0000005: Access violation writing location 0x00000040.当使用指针向双向链表添加新信息时,我假设新联系人为空。这是我完成函数的地方:

curr->next = newContact;
newContact->prev = curr;
newContact->next = NULL;

所以我添加了以下 if..else 循环来检查 curr 是否等于 newContact 并将其添加到列表中。但这也不起作用..

if(curr-> newContact)
{
    curr->next = newContact;
    newContact->prev = NULL;
}
else
{
curr->next = newContact;
newContact->prev = curr;
newContact->next = NULL;
}

这是完整的功能供参考:

 int addContact(struct contact *theList)
    {
        struct contact *newContact, *curr;

        // create the new structure
        newContact = (struct contact *)malloc(sizeof(struct contact));
        if( newContact == NULL )
        {   // if true, then no memory left - oops
            return(0);
        }
        // find the end of the list
        curr = theList;
        // scroll through the list 
        if(curr != NULL)
        {

            while( curr->next != NULL)
            {
                curr = curr->next;
            }

        }
        // now have the last contact
        // add the new one here.
        printf("\nEnter a surname: ");
        fflush(stdin);
        gets(newContact->sname);
        printf("\nEnter a first name: ");
        gets(newContact->fname);
        printf("\nEnter a phone: ");
        gets(newContact->phone);
        printf("\nEnter a company: ");
        gets(newContact->company);

        // need to hook the new contact to
        // end of list

        if(curr-> newContact)
        {
            curr->next = newContact;
            newContact->prev = NULL;


        }
        else
        {
        curr->next = newContact;
        newContact->prev = curr;
        newContact->next = NULL;
        }
        return(1);
    }//add

我看不到支票哪里出了问题。有什么想法吗?谢谢

4

1 回答 1

1

访问冲突和0x00000040错误消息中的地址告诉您您没有正确初始化curr它是指向某种结构的指针。很可能您声明了它,但从未为其分配内存或将其设置为指向有效的存储空间。

我敢打赌,在结构中curr是0x40 字节的钱。NULLnext

扩展您编辑的问题...看看这段代码...如果curr NULL会发生什么?你正在测试这种可能性,但如果是,NULL你就什么也不做。

   // find the end of the list
    curr = theList;
    // scroll through the list 
    if(curr != NULL)
    {

        while( curr->next != NULL)
        {
            curr = curr->next;
        }

    }
于 2013-04-26T13:52:13.873 回答