所以,我有一些代码,类似于下面的代码,可以将一个 struct 添加到一个 struct 列表中:

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
}

这些 struct 的定义如下:

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仍然指向空的_列表,而不是barPush内部创建的修改版本.如果我想修改这个列表,我需要把它作为一个指向指针的指针传递进go 吗?还是需要一些其他的黑暗咒语?

推荐答案

如果要执行此操作,则需要传入指向指针的指针.

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)建议在 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++相关问答推荐

C中的整字母后缀i是什么

与unions 的未定义行为

ATmega328P USART发送字符重复打印

如何在C宏中确定Windows主目录?

编译的时候g++通常会比GCC慢很多吗?

如何在IF语句中正确使用0.0

识别和处理c中整数溢出的最佳方法?

C lang:当我try 将3个或更多元素写入数组时,出现总线错误

C语言编译阶段与翻译阶段的关系

文件权限为0666,但即使以超级用户身份也无法打开

如何在CANbus RX/TX FIFO起始地址寄存器(ATSAME 51)的特定地址初始化数组?

有什么方法可以将字符串与我们 Select 的子字符串分开吗?喜欢:SIN(LOG(10))

如何在C-函数中混合使用C代码和ASM?

我在C中运行和调试时得到了不同的输出

如何将大写/小写土耳其字母相互转换?

如何修复我的qsort()算法?它每次都给出不同的结果

在文件描述符上设置FD_CLOEXEC与将其传递给POSIX_SPOWN_FILE_ACTIONS_ADCLOSE有区别吗?

C struct 中的冒泡排序

将指针的地址加载到寄存器内联拇指组件中

函数的typedef是标准 C 语法吗?它与函数指针的typedef有何不同?