动态数组分配和复制到更大

时间:2012-01-30 22:42:13

标签: c arrays

我正在完成一项家庭作业,我正试图找到一个很好的方法。

我想复制一个类型为“dog”的动态数组,其中包含两个结构的值到另一个大小两倍的“临时”动态数组。完成后,我希望原始数组名称替换“临时”

pseudo: 
user inserts some newnum of elements ->call to func
check if sizeof(array) < (n_items + newnum)
yes: need to grow array
//here's the trouble part
create temp.array 2x sizeof(dog.array), copy dog.array to bigger temp.array
//would i be better off free(dog.array) and then create a new instance of
//dog.array that is now the same size of the temp.array and copy again/free(temp)
//or is there another method to do "new" dog.array = temp.array

当我的程序检查空间以向此数组中插入更多值时,它将继续并分配一个大小为两倍的新数组(如果第一个已满)。在此之后,它在for循环中交换数据,这很好。我很好奇如何释放旧的已分配空间,然后重命名新的“temp”数组以匹配旧的数据......或者只是删除与旧数组关联的数据,并简单地创建一个具有相同名称的指针“临时”的。不确定如何解决这个问题。

1 个答案:

答案 0 :(得分:2)

Take a look at the realloc() function,它允许您更改分配给您感兴趣的指针的内存量。或者你可以在第二个不同的指针上执行malloc(),从第一个指针到第二个指针memcpy()个字节,然后free()第一个指针。这取决于你。