2016-03-15 36 views
1

我想在循环中创建结构并将它们传递给函数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. 显然存储的这种方式是不可能的,因为我不能保存指针s在数组中。但是,我不知道该怎么做。它是如何工作的?

  2. 循环将在下一次迭代中覆盖s指针。我不希望global_array中的数据发生变化。我怎样才能做到这一点?我需要在foo中创建s的深层副本吗?

  3. 后来我不会使用global_array,我想释放内存。只需简单地拨打free(global_array)即可释放实际内容,即事先存储在其中的所有结构。

回答

0

如果你想跟踪的指针,你的全局数组不应是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; 

然后,当你清理,首先free每个阵列成员,则阵列本身:

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

在下一次循环迭代中覆盖指针时没有问题吗?分配的内存仍然存在,但没有内存泄漏,因为我将指针保存在数组中。它是否正确? – null

+0

正确。您将指针值传递给将其保存在全局数组中的函数,因此不会泄漏。只要你最终释放全球名单,你就没事。 – dbush

+2

@null - 另请注意,此解决方案仅适用于阵列中固定数量的“大小”条目。所以你或者需要确保'index'永远不会超过数组的末尾--OR--当它发生时使用'realloc'来增长你的数组。 –

-1

要保存数组中的指针,您需要使用指针数组。类似这样的:

// Notice no cast from malloc 
my_struct** global_array = malloc(size * sizeof(my_struct*)); 

这将需要您释放指向对象的指针,然后释放该数组。像这样:

for (size_t i = 0; i < size, ++i) 
    free(global_array[i]); 
free(global_array); 
+0

我的回答有什么问题? – SergeyA

0

您有概述的解决方案基本上是健全的(全局数组的声明是不正确的)。

要回答你的问题。 1.是的,您可以将指针存储在数组中。 2.存储在全局数组中的数据不会改变。您可能不需要进行深层复制(我不能肯定地说,因为您未显示您计划将值赋予memb1和memb2)。 3.您需要释放阵列的每个元素,然后释放阵列。

作为一个以前的答案已经表示,全球阵列的声明是不正确,应该是这样的:

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

malloc返回指针的演员是可选的,我认为大小等于到1000.

相关问题