【问题标题】:C linked list Access violationC链表访问冲突
【发布时间】:2012-10-11 08:09:53
【问题描述】:

我用指针和函数制作了这个程序,它应该是一个链表。我不断收到“访问冲突读取位置 0xcdcdcded”。在下面的最后一部分。我认为可能是我接下来没有初始化,但我是指针新手,不知道该怎么做。任何帮助是极大的赞赏。

typedef struct temp 
{
    char name[20];
    char telephone[10];
    temp *next;
} node;


node* creation1 ()
{    
    node *NEW = NULL;
    NEW = (node*)malloc(sizeof(node)); 
    return NEW;
}

node* creation2 ()
{   
    node *start= NULL;
    node *NEW = creation1();
    start= NEW;
    return start;
}

node* creation3 ()
{    
    node *NEW = creation1();
    node *current = NULL;
    current=NEW;
    return current;
} 

void consult ()
{   
    node *NEW= creation1();
    node *start= creation2();
    node *current = creation3();
    int exit;
    printf("How many contacts do you wish to add? ");
    scanf("%i",&exit);

    for(int i=1; i<=exit; i++)
    {
        NEW = (node*)malloc(sizeof(node));
        current->next=NEW;                 
        current = NEW; 
        fflush(stdin);
        puts("NAME: ");
        gets(NEW->name); 
        puts("TELEPHONE: ");
        gets(NEW->telephone);
        NEW->next=NULL;
    } 

    current=start->next;

    int i = 0;
    do 
    {
        i++;
        current = current->next; //this is where it stops and gives me the access reading violation
    }while (current != NULL);
}

int main(int argc, char** argv)
{  
    consult();
}

【问题讨论】:

    标签: list pointers linked-list access-violation


    【解决方案1】:

    由于这似乎是家庭作业,我不想透露太多,但您的基本问题是您首先使用node *start= creation2(); 行创建一个起始节点。在执行的这一点上,start-&gt;next 的值是垃圾,可以是任何东西。

    然后,在你的 for 循环中,start 节点根本没有被触及,这意味着 start-&gt;next 仍然可以是任何东西。

    接下来,在current=start-&gt;next; 行中,您将current 设置为start-&gt;next 的垃圾值。

    最后在current = current-&gt;next; 行中,您正在取消引用垃圾值并跳转到内存中的随机位置。

    一般来说,如果你有一个指针值(例如start-&gt;next),而你在创建它时没有一个好的值来设置指针,你应该将它设置为NULL。然后,在取消引用一个值之前(使用-&gt; 运算符),您应该检查-&gt; 左侧的变量是否等于NULL,如果是,则不要执行@ 987654334@操作。我真的很难给出任何更具体的建议,因为您的代码中没有 cmets 来解释应该发生的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2017-03-28
      • 1970-01-01
      • 1970-01-01
      • 2018-04-16
      相关资源
      最近更新 更多