C에서 함수로 전달 된 포인터를 어떻게 수정합니까?
-
12-09-2019 - |
문제
그래서, 나는 다음과 같은 코드가 있습니다.
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);
그러나 그 후에도 B Barpush 내부에서 생성 된 수정 된 버전이 아니라 여전히 빈_list를 가리 킵니다. 수정하려면 포인터에 대한 포인터로 목록을 전달해야합니까, 아니면 다른 어두운 주문이 필요한가?
해결책
이 작업을 수행하려면 포인터를 포인터로 전달해야합니다.
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 * l;
l = EMPTY_LIST;
barPush(&l,&b1); // b1 and b2 are just Bar's
barPush(&l,&b2);
Jonathan Leffler는 다음 의견에서 목록의 새로운 헤드를 반환 할 것을 제안했습니다.
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);
다른 팁
일반적인 답변 : 변경하려는 것에 대한 포인터를 전달하십시오.
이 경우 변경하려는 포인터에 대한 포인터입니다.
C에서는 모든 것이 가치로 전달됩니다.
당신은 이와 같은 포인터로 포인터를 전달합니다.
int myFunction(int** param1, int** param2) {
// now I can change the ACTUAL pointer - kind of like passing a pointer by reference
}
예, 포인터를 포인터로 전달해야합니다. C는 참조가 아니라 값으로 인수를 전달합니다.
이것은 고전적인 문제입니다. 할당 된 노드를 반환하거나 포인터 포인터를 사용하십시오. C에서는 X를 X를 수정하려는 함수로 X로 전달해야합니다. 이 경우 포인터를 수정하려면 포인터를 포인터로 전달해야합니다.
제휴하지 않습니다 StackOverflow