c - 如何修改已传递给 C 函数的指针?

标签 c function pointers parameters 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
}

这些结构定义如下:

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 - 如何修改已传递给 C 函数的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51688980/

相关文章:

c - c 中传递指针警告

C 函数在给定索引的情况下交换文本文件中的两行

c++ - 用OpenGL绘制位图字体,glRasterPos2i()有什么作用?

c -/proc/self/映射到实际代码的段

c - 如何在C中一一获取字符串的输入

检查list2是否包含list1

c - 将一个字符串复制到另一个字符串的程序(包含该函数)正在打印奇怪的字符

c - 这是错误的还是我遗漏了什么(int count = 10, x;)

python - 在 Python 中赋值之前引用的局部变量

c - 在c中使用运算符 '->'的奇怪副作用