2009-04-20 9 views
34

그래서 구조체 목록에 구조체를 추가하려면 다음과 같은 코드가 필요합니다.C에서 함수로 전달 된 포인터를 어떻게 수정합니까?

void barPush(BarList * list,Bar * bar) 
{ 
    // if there is no move to add, then we are done 
    if (bar == NULL) return;//EMPTY_LIST; 

    // allocate space for the new node 
    BarList * newNode = malloc(sizeof(BarList)); 

    // assign the right values 
    newNode->val = bar; 
    newNode->nextBar = list; 

    // and set list to be equal to the new head of the list 
    list = newNode; // This line works, but list only changes inside of this function 
} 

이 구조체는 다음과 같이 정의됩니다.

typedef struct Bar 
{ 
    // this isn't too important 
} Bar; 

#define EMPTY_LIST NULL 

typedef struct BarList 
{ 
    Bar * val; 
    struct BarList * nextBar; 
} BarList; 

그런 다음 다른 파일 나는 다음과 같은 일을한다.

BarList * l; 

l = EMPTY_LIST; 
barPush(l,&b1); // b1 and b2 are just Bar's 
barPush(l,&b2); 

그러나이 후에도 l은 여전히 ​​barPush 안에 만들어진 수정 된 버전이 아니라 EMPTY_LIST를 가리킨다. 포인터를 수정하고 싶을 때 포인터를 포인터로 전달해야합니까? 아니면 다른 암술이 필요합니까?

답변

41

처럼 포인터에 대한 포인터를 전달합니다.

void barPush(BarList ** list,Bar * bar) 
{ 
    if (list == NULL) return; // need to pass in the pointer to your pointer to your list. 

    // if there is no move to add, then we are done 
    if (bar == NULL) return; 

    // allocate space for the new node 
    BarList * newNode = malloc(sizeof(BarList)); 

    // assign the right values 
    newNode->val = bar; 
    newNode->nextBar = *list; 

    // and set the contents of the pointer to the pointer to the head of the list 
    // (ie: the pointer the the head of the list) to the new node. 
    *list = newNode; 
} 

다음과 같이 사용 :

BarList *barPush(BarList *list,Bar *bar) 
{ 
    // if there is no move to add, then we are done - return unmodified list. 
    if (bar == NULL) return list; 

    // allocate space for the new node 
    BarList * newNode = malloc(sizeof(BarList)); 

    // assign the right values 
    newNode->val = bar; 
    newNode->nextBar = list; 

    // return the new head of the list. 
    return newNode; 
} 

사용이된다 :

BarList * l; 

l = EMPTY_LIST; 
l = barPush(l,&b1); // b1 and b2 are just Bar's 
l = barPush(l,&b2); 
+1

덕분에, 나는이 문제를 생각 했어요 싶지만, 그것이 아니라는 것을 희망, –

+3

는 다른 방법으로, 함수가리스트의 새로운 헤드 포인터를 반환해야). BarList * barPush (BarList * 목록, Bar * bar) –

2

예, 당신은 포인터에 대한 포인터를 전달해야합니다. C는 참조가 아닌 값으로 인수를 전달합니다.

6

는 C에서, 모든 값에 의해 전달되는 기억.

당신은이 작업을 수행하려는 경우가 포인터로 포인터를 전달하기 위해 필요한이

int myFunction(int** param1, int** param2) { 

// now I can change the ACTUAL pointer - kind of like passing a pointer by reference 

} 
2

BarList * l; 

l = EMPTY_LIST; 
barPush(&l,&b1); // b1 and b2 are just Bar's 
barPush(&l,&b2); 

조나단 레플러는 의견 목록의 새로운 머리를 반환 제안

이것은 고전적인 p입니다. 흠집. 할당 된 노드를 반환하거나 포인터 포인터를 사용하십시오. C에서는 X를 수정하려는 함수에 X에 대한 포인터를 전달해야합니다. 이 경우 포인터를 수정하려면 포인터에 포인터를 전달해야합니다.

14

일반 대답 : 당신이 변경하려는 일에 대한 포인터를 전달합니다. 이 경우

, 그것은 변경할 포인터에 대한 포인터가 될 것입니다.

관련 문제