访问冲突将数据写入双向链表

时间:2013-04-26 13:49:02

标签: c pointers function-pointers doubly-linked-list

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

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

所以我添加了以下if..else循环来检查curr是否等于newContact并将其添加到list.But也不起作用..

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

我无法看到我在支票上出错了。有什么想法吗?谢谢

1 个答案:

答案 0 :(得分:1)

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

我认为currNULLnext为结构中的0x40字节的钱。

扩展您已修改的问题...查看此代码块...如果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;
        }

    }