2012-10-21 6 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; 줄에 currentstart->next의 쓰레기 값으로 설정합니다.

마지막으로 current = current->next; 라인에서 가비지 값을 역 참조하고 메모리의 임의의 위치로 점프합니다.

일반적으로 포인터 값 (예 : start->next)이 있고 포인터를 만들 때 포인터를 설정할 가치가없는 경우 NULL으로 설정해야합니다. 그런 다음 값을 역 참조하기 전에 (-> 연산자 사용) ->의 왼쪽에있는 변수가 NULL과 같은지 확인하고, 그렇다면 -> 작업을 수행하지 마십시오. 더 구체적인 조언은 정말 어렵습니다. 코드에 어떤 내용을 설명해야하는지에 대한 설명이 없기 때문입니다.