C: 用 malloc 扩展数组 [英] C: Expanding an array with malloc

查看:59
本文介绍了C: 用 malloc 扩展数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm a bit new to malloc and C in general. I wanted to know how I can, if needed, extend the size of an otherwise fixed-size array with 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;
}

  • 上面的例子应该清楚我想要完成什么.
  • (顺便说一句:我写的解释器需要这个:使用固定数量的变量,如果需要更多变量,只需动态分配它们)

    (By the way: I need this for an interpreter I write: Work with a fixed amount of variables and in case more are needed, just allocate them dynamically)

    推荐答案

    使用 realloc,但你必须先用 malloc 分配数组.在上面的例子中,你是在堆栈上分配它.

    Use realloc, but you have to allocate the array with malloc first. You're allocating it on the stack in the above example.

       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 扩展数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆