gpt4 book ai didi

c - 使用 malloc 扩展数组

转载 作者:太空狗 更新时间:2023-10-29 16:27:34 25 4
gpt4 key购买 nike

总的来说,我对 malloc 和 C 有点陌生。我想知道如何在需要时使用 malloc 扩展固定大小数组的大小。

例子:

#define SIZE 1000
struct mystruct
{
int a;
int b;
char c;
};
mystruct myarray[ SIZE ];
int myarrayMaxSize = SIZE;
....
if ( i > myarrayMaxSize )
{
// malloc another SIZE (1000) elements
myarrayMaxSize += SIZE;
}
  • 上面的例子应该清楚我想要完成什么。

(顺便说一句:我写的解释器需要这个:使用固定数量的变量,如果需要更多,只需动态分配它们)

最佳答案

使用realloc , 但你必须先用 malloc 分配数组。在上面的示例中,您将它分配到堆栈上。

   size_t myarray_size = 1000;
mystruct* myarray = malloc(myarray_size * sizeof(mystruct));

myarray_size += 1000;
mystruct* myrealloced_array = realloc(myarray, myarray_size * sizeof(mystruct));
if (myrealloced_array) {
myarray = myrealloced_array;
} else {
// deal with realloc failing because memory could not be allocated.
}

关于c - 使用 malloc 扩展数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2748036/

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