C: Expanding an array with malloc

后端 未结 4 991
逝去的感伤
逝去的感伤 2020-12-08 07:53

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.

Example:



        
4条回答
  •  無奈伤痛
    2020-12-08 08:37

    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.
       }
    

提交回复
热议问题