总的来说,我对 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/