gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:03:07 27 4
gpt4 key购买 nike

我正在做家庭作业,我想找出解决这个问题的好方法。

我想复制一个类型为“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”数组以匹配旧的……或者只是删除与旧数组关联的数据,然后简单地创建一个同名的指针“温度”之一。不确定该怎么做。

最佳答案

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

关于c - 动态数组分配和复制到更大的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9071928/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com