如何修改传递给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 NULLtypedef struct BarList{
Bar * val;
struct BarList * nextBar;} BarList;然后在另一个文件中执行如下操作:BarList * l;l = EMPTY_LIST;barPush(l,&b1); // b1 and b2 are just Bar'sbarPush(l,&b2);但是,在此之后,l仍然指向空_list,而不是barPush内部创建的修改版本。如果我想修改一个指针,是否必须将列表作为指针传入,还是需要使用其他暗咒语?
3 回答
函数式编程
TA贡献1807条经验 获得超9个赞
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'sbarPush(&l,&b2);
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'sl = barPush(l,&b2);
幕布斯6054654
TA贡献1876条经验 获得超7个赞
int myFunction(int** param1, int** param2) {// now I can change the ACTUAL pointer - kind of like passing a pointer by reference }
- 3 回答
- 0 关注
- 622 浏览
添加回答
举报
0/150
提交
取消