2014-11-12 3 views
1

나는 내 코드의 버그로 혼란스러워했다. 연결된 목록을 만들고 요소를 추가하려면 push()을 사용하고 요소를 출력하려면 printList()을 사용하십시오. 아래 코드는 올바르게 작동합니다. 나는 printList() 함수를 호출이중 포인터 (**)와 단일 포인터 (*)로 전달되는 인수

void push(linkedList_t* listHead, int new_data) 
{ 
    /* allocate node */ 
    linkedList_t* new_node = 
     (linkedList_t *) malloc(sizeof(linkedList_t)); 

    /* put in the data */ 
    new_node->_Value = new_data; 

    /* link the old list off the new node */ 
    new_node->_Next = listHead; 

    /* move the head to point to the new node */ 
    listHead = new_node; 
} 

, 아무 일도, 내가 headNULL하지만 난에 같게 유지 때문에 그것이 생각 :

#include <stdio.h> 
#include <stdlib.h> 
struct linkedList { 
    int   _Value; 
    struct linkedList * _Next; 
}; 
typedef struct linkedList linkedList_t; 

/* Function to push a node */ 
void push(linkedList_t** listHead, int new_data) 
{ 
    /* allocate node */ 
    linkedList_t* new_node = 
     (linkedList_t *) malloc(sizeof(linkedList_t)); 

    /* put in the data */ 
    new_node->_Value = new_data; 

    /* link the old list off the new node */ 
    new_node->_Next = *listHead; 

    /* move the head to point to the new node */ 
    *listHead = new_node; 
} 


/* Function to print linked list */ 
void printList(linkedList_t *head) 
{ 
    linkedList_t *tmp = head; 
    while (tmp != NULL) 
    { 
     printf("%d ", tmp->_Value); 
     tmp = tmp->_Next; 
    } 
} 
int main(int argc, char* argv[]) 
{ 
    linkedList_t *head = NULL; 
    push(&head, 20); 
    push(&head, 4); 
    push(&head, 15); 
    push(&head, 85); 
    printList(head); 
    return 0; 
    } 

문제는 내가 인수를 변경할 때 하나의 포인터 등이다 내 코드에서 무엇이 잘못되었는지 알 수 없으므로 에서 push()을 호출하고 내 main function을으로 명명하면 다음과 같이 가정합니다.

int main(int argc, char* argv[]) 
{ 
    linkedList_t *head = NULL; 
    push(head, 20); 
    push(head, 4); 
    push(head, 15); 
    push(head, 85); 
    printList(head); 
    return 0; 
    } 

몇 가지 제안이 필요했습니다. 아무도 도움이 필요합니까? 감사!

+0

'listHead = new_node,'호출자가 제공하는 포인터에 절대 영향을주지 않습니다 이 함수에 전달되었습니다. 따라서 두 번째 스 니펫이 작동하지 않는 이유는 무엇입니까? 어떻게 든, 어떤 식 으로든, 당신은 list head pointer * value *의 잠재적 인 변화를 호출자에게 되돌려 줄 필요가 있습니다. 이것은 일반적으로 pointer-to-pointer를 전달하거나 새로운 list-head를 반환함으로써 수행됩니다 (후자는 반환 결과를 저장하는 것을 기억하기 위해 호출자에게 부담을 주므로 다소 경멸 스럽습니다). 당신은 * [** this **] (http://stackoverflow.com/a/15244661/1322972) 흥미로운 읽기, 특히 두 번째 단락을 찾을 수 있습니다. – WhozCraig

답변

1

단일 포인터를 사용할 때 실제로 헤드 포인터의 복사본을 전달합니다. 이중 포인터의 경우 머리 포인터의 주소를 전달하므로 변경이 가능합니다.

분 변경으로 단일 포인터 버전으로 코드 작업을 할 수 있습니다. 이 경우 푸시 기능에서 헤드 포인터를 반환해야합니다. 이 경우 변화에

linkedList_t* push(linkedList_t* listHead, int new_data); 

가 될 것이다 반영 : -

linkedList_t *head = NULL; 
head = push(head, 20); 
head = push(head, 4); 

희망 나는 ... 충분히 명확입니다