2012-10-21 141 views
0

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

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(); 
} 

回答

0

因为这似乎是它可能功课,我不想透露太多,但你的基本问题是,你首先要创建一个开始节点与线路node *start= creation2();。在执行的这一点上,start->next的值是垃圾,可能是任何东西。

然后,在您的for循环中,根本不触及节点start,这意味着start->next仍然可以是任何东西。

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

然后最后在行current = current->next;您正在解引用垃圾值并跳转到内存中的随机位置。一般来说,如果你有一个指针值(如start->next),并且你没有很好的值来设置指针在你创建时的值,你应该把它设置为NULL。然后,在取消引用值(使用->运算符)之前,应检查->左侧的变量是否等于NULL,如果是,则不要执行->操作。任何更具体的建议对我来说都很难,因为代码中没有任何注释来解释应该发生的事情。