c - 如何使用适当的内存管理将动态创建的结构保存在数组中?

标签 c struct

我想在循环中创建结构并将它们传递给函数 foo。然后该函数应该处理结构数据并将结构保存在数组中以供以后重用。

// create structs in a loop
for(int i=0; i<1000); i++) {
    my_struct* s = (my_struct*) malloc(sizeof(my_struct));
    s->memb1 = "foo"; // this data will change in each iteration
    s->memb2 = "bar"; // only for simplicity here

    store_in_array(s);
}

// ...
my_struct* global_array = (my_struct*) malloc(size * sizeof(my_struct));

int foo(my_struct* s) {

    // process s in some way
    // ...

    // store s it for later use in array
    global_array[index] = s; // boom
}
  1. 显然这种存储方式是行不通的,因为我无法在数组中保存指向a s 的指针。但是,我不知道该怎么做。它是如何工作的?

  2. 循环将在下一次迭代中覆盖 s 指针。我不想更改 global_array 中的数据。我怎样才能做到这一点?我是否需要在 foo 中创建 s 的深拷贝?

  3. 稍后我不会使用 global_array 并且我想释放内存。仅调用 free(global_array) 来释放实际内容是否足够,即我事先存储在其中的所有结构。

最佳答案

如果你想跟踪指针,你的全局数组不应该是 my_struct 的数组,就像你设置的那样,而是 my_struct * 的数组>.

// don't cast the return value of malloc
my_struct **global_array = malloc(size * sizeof(my_struct *));
      //  ^---- note the placement of ** with the variable instead of the type name
      // this reduces ambiguity

然后你可以像这样添加到数组中,假设 index 是数组的当前大小:

global_array[index++] = s;

然后当你清理时,你首先释放每个数组成员,然后是数组本身:

int i;
for (i=0 i<index; i++) {
    free(global_array[i]);
}
free(global_array);

关于c - 如何使用适当的内存管理将动态创建的结构保存在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36018471/

相关文章:

c - 从长度未知的字符串中读取所有 double

c++ - 错误 LNK2005 : xxx already defined in MSVCRT. lib(MSVCR100.dll) C :\something\LIBCMT. lib(setlocal.obj)

c++ - 访问私有(private)数据类型

c - 尝试使用调用 stat 的 ctime 返回值对 c 中的结构数组进行排序

c++ - Netbeans C/C 不编译

c - 信号 11 (SIGSEGV)

C++ Stack Push 方法不将结构插入堆栈,只返回 0

c# - 等价于 C# 的 C++ typedef 结构

c - 使用 iptables TPROXY 重定向到原始套接字

c - 使用 typedef 和结构理解 C 代码