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

查看:275
本文介绍了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;
}


  • 上面的例子应该清楚我想要完成的任务。

  • (顺便说一句:我需要这个跨preTER我写的:与变量的情况下,更需要一个固定数额的工作,只是它们分配动态)

    (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天全站免登陆