所以,我有一些代码,类似于以下,将结构添加到结构列表:
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仍然指向EMPTY_LIST,而不是barPush内部创建的修改版本 . 如果我想修改它,或者是否需要其他暗咒语,我是否必须将列表作为指针传递给指针?
5 回答
如果要执行此操作,则需要传入指针指针 .
然后像这样使用它:
Jonathan Leffler建议在评论中返回名单的新负责人:
用法变为:
通用答案:将指针传递给您想要更改的内容 .
在这种情况下,它将是指向您想要更改的指针的指针 .
请记住,在C中,一切都是按值传递的 .
你传入指向指针的指针,就像这样
是的,你必须传入一个指针指针 . C按值传递参数,而不是通过引用传递参数 .
这是一个经典问题 . 返回已分配的节点或使用指针指针 . 在C中,您应该将指向X的指针传递给您希望修改X的函数 . 在这种情况下,由于您希望修改指针,因此您应该将指针传递给指针 .