그래서 구조체 목록에 구조체를 추가하려면 다음과 같은 코드가 필요합니다.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를 가리킨다. 포인터를 수정하고 싶을 때 포인터를 포인터로 전달해야합니까? 아니면 다른 암술이 필요합니까?
덕분에, 나는이 문제를 생각 했어요 싶지만, 그것이 아니라는 것을 희망, –
는 다른 방법으로, 함수가리스트의 새로운 헤드 포인터를 반환해야). BarList * barPush (BarList * 목록, Bar * bar) –