Pau*_*cks 49 c pointers pass-by-value
所以,我有一些代码,类似于以下,将结构添加到结构列表:
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
}
Run Code Online (Sandbox Code Playgroud)
这些结构定义如下:
typedef struct Bar
{
// this isn't too important
} Bar;
#define EMPTY_LIST NULL
typedef struct BarList
{
Bar * val;
struct BarList * nextBar;
} BarList;
Run Code Online (Sandbox Code Playgroud)
然后在另一个文件中,我执行以下操作:
BarList * l;
l = EMPTY_LIST;
barPush(l,&b1); // b1 and b2 are just Bar's
barPush(l,&b2);
Run Code Online (Sandbox Code Playgroud)
但是,在此之后,l仍然指向EMPTY_LIST,而不是barPush内部创建的修改版本.如果我想修改它,或者是否需要其他暗咒语,我是否必须将列表作为指针传递给指针?
geo*_*tnz 54
如果要执行此操作,则需要传入指针指针.
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;
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它:
BarList * l;
l = EMPTY_LIST;
barPush(&l,&b1); // b1 and b2 are just Bar's
barPush(&l,&b2);
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
用法变为:
BarList * l;
l = EMPTY_LIST;
l = barPush(l,&b1); // b1 and b2 are just Bar's
l = barPush(l,&b2);
Run Code Online (Sandbox Code Playgroud)
Ant*_*ony 13
请记住,在C中,一切都按值传递.
你传入指向指针的指针,就像这样
int myFunction(int** param1, int** param2) {
// now I can change the ACTUAL pointer - kind of like passing a pointer by reference
}
Run Code Online (Sandbox Code Playgroud)
这是一个经典问题。要么返回分配的节点,要么使用指针的指针。在 C 中,您应该将指向 X 的指针传递给您想要修改 X 的函数。在这种情况下,由于您想要修改指针,因此应该将指针传递给指针。