我想在循环中创建结构并将它们传递给函数 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
}
显然这种存储方式是行不通的,因为我无法在数组中保存指向a
s
的指针。但是,我不知道该怎么做。它是如何工作的?循环将在下一次迭代中覆盖 s 指针。我不想更改
global_array
中的数据。我怎样才能做到这一点?我是否需要在foo
中创建s
的深拷贝?稍后我不会使用
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/