C 如何在给定变量作为引用的函数中初始化结构

C 如何在给定变量作为引用的函数中初始化结构,c,struct,reference,C,Struct,Reference,我对c还是有点陌生,我正在尝试为函数中的结构分配一些内存,并通过引用传递它 我的解决方案不起作用,因为我在那里初始化的结构没有传递给其他函数,并且我在尝试访问未分配的内存时出错 下面是有问题的代码: #include <stdlib.h> typedef struct list list; struct list { int x; }; void init_list(list* mylist){ mylist = malloc(sizeof(list));

我对c还是有点陌生,我正在尝试为函数中的结构分配一些内存,并通过引用传递它

我的解决方案不起作用,因为我在那里初始化的结构没有传递给其他函数,并且我在尝试访问未分配的内存时出错

下面是有问题的代码:


#include <stdlib.h>

typedef struct list list;

struct list {
     int x;
};

void init_list(list* mylist){
    mylist = malloc(sizeof(list));
    mylist->x = 1;
}

void free_list(list* mylist){
    free(mylist);
}

main(){
    list mylist;
    init_list(&mylist);

    //use the value of x for something

    free_list(&mylist); 
}

在这种情况下,其他函数可以访问结构,但我无法释放它,因为我没有正确的指针。当我试着运行它时,它只是说释放无效大小

那么在这种情况下,分配内存和传递地址的正确方法是什么呢? 我也知道我可以直接返回它,但我想知道它是否以及如何通过引用实现

我也在使用clang进行编译

提前感谢。

当您调用init_list时,它会分配一个与struct list大小相同的内存块,并将x的值设置为1。你做得很好。但是您的函数的输入似乎有点问题。在C语言中,当你把一个参数传递给一个函数时,你实际上传递了它的一个副本。更改函数内的值不会更改main中的值。这意味着您传递给函数的内容必须是您希望函数更改的内容的引用。在这种情况下,您希望函数在调用malloc时更改指向结构列表的指针。你正在寻找的工作是这样的:

int main(void) {
list *pointer_to_list; //declares pointer, NOT a struct
init_list(&pointer_to_list); //passes the reference value of the pointer (essentially a 'struct list**')
free_list(pointer_to_list);
}
其中,初始列表定义为:

void init_list(list **mylist) {
*mylist = malloc(sizeof(list)); //sets the pointer called pointer_to_list in main() to the ouput of malloc()
(**mylist).x = 1;

//Note that we never change the value of mylist
//because it won't change anything in main() anyway
}

您可能希望发布实际编译的代码。看。好的,我编辑了它,现在可以运行了。我试着编译代码,得到了4个警告和7个错误。所以仍然无法运行代码。哦,是的,我的错。主功能没有包含括号。我在自己的代码中有它们,但忘了将它们放在这里。编译时,始终启用警告,然后修复这些警告。对于gcc,至少使用:-Wall-Wextra-Wconversion-pedantic-std=gnu11注意:其他编译器使用不同的选项来生成相同的内容。
void init_list(list **mylist) {
*mylist = malloc(sizeof(list)); //sets the pointer called pointer_to_list in main() to the ouput of malloc()
(**mylist).x = 1;

//Note that we never change the value of mylist
//because it won't change anything in main() anyway
}