如何修改已经传递到C中的函数指针? [英] How do I modify a pointer that has been passed into a function in C?
问题描述
所以,我有一些code,有点像下面一个struct添加到结构的列表:
So, I have some code, kind of like the following, to add a struct to a list of structs:
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
}
这些结构定义如下:
These structures are defined as follows:
typedef struct Bar
{
// this isn't too important
} Bar;
#define EMPTY_LIST NULL
typedef struct BarList
{
Bar * val;
struct BarList * nextBar;
} BarList;
,然后在另一个文件中我做类似以下内容:
and then in another file I do something like the following:
BarList * l;
l = EMPTY_LIST;
barPush(l,&b1); // b1 and b2 are just Bar's
barPush(l,&b2);
然而,在此之后,L仍然指向EMPTY_LIST,不barPush的内部创建的修改后的版本。我必须在通过列表作为指针的指针,如果我想修改它,还是有一些要求的其他黑暗咒语?
However, after this, l still points to EMPTY_LIST, not the modified version created inside of barPush. Do I have to pass list in as a pointer to a pointer if I want to modify it, or is there some other dark incantation required?
推荐答案
您需要一个指针传递给一个指针,如果你想做到这一点。
You need to pass in a pointer to a pointer if you want to do this.
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;
}
然后使用它是这样的:
Then use it like this:
BarList * l;
l = EMPTY_LIST;
barPush(&l,&b1); // b1 and b2 are just Bar's
barPush(&l,&b2);
乔纳森·莱弗勒提出的意见返回列表的新掌门人:
Jonathan Leffler suggested returning the new head of the list in the comments:
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中的函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!