题
因此,我有一些代码,有点像以下内容,可以在结构列表中添加结构:
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内部创建的修改版本。如果我想修改指针,我是否必须将列表作为指针将其传递给指针,还是需要其他一些黑暗的咒语?
解决方案
如果要执行此操作,则需要将指针传递给指针。
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的功能。在这种情况下,由于您希望修改指针,因此您应该将指针传递给指针。
不隶属于 StackOverflow