c - 如何在以变量作为引用的函数内初始化结构

标签 c struct reference

我对 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); 
}

我尝试这样做:

init_list(list* mylist){
   list *temp = malloc(sizeof(list));
   -initiliaze variables-
   *mylist = *temp
}

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

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

我也使用 clang 进行编译。

提前致谢。

最佳答案

当你调用init_list()时,它会分配一个struct list大小的内存块,并将x的值设置为1。你就可以了。但你的函数输入似乎有点问题。当您将参数传递给 C 中的函数时,您实际上传递的是它的副本。更改函数内部的值不会更改 main() 中的值。这意味着您传递给函数的内容必须是对您希望函数更改的内容的引用。在这种情况下,您希望函数在调用 malloc() 时将指针更改为 struct list。您正在寻找的解决方法是这样的:

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);
}

其中 init_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
}

关于c - 如何在以变量作为引用的函数内初始化结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59977164/

相关文章:

c - 在curses 模式之外使用getch 的可移植性如何?

c++ - 如何在结构或类的 vector 中快速搜索具有特定值的对象? C++

c++ - 具有类成员的结构的静态初始化

vector - 如何在 Rust 中声明 &[&T]]?

c++ - MinGW "undefined reference to IMG_Load/IMG_Init/IMG_Quit"LazyFoo

c - MPI 上的并行数组加法

c - 更多位 : Efficiently implementing a binary search over a fixed-size array

c - 接收从 "supernet"发送的本地广播包

c++ - 检索头文件中定义的结构列表

ios - 通过引用传递的对象将不存在。 swift