C: Expanding an array with malloc

后端 未结 4 994
逝去的感伤
逝去的感伤 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:47

    You want to use realloc (as other posters have already pointed out). But unfortunately, the other posters have not shown you how to correctly use it:

    POINTER *tmp_ptr = realloc(orig_ptr, new_size);
    if (tmp_ptr == NULL)
    {
        // realloc failed, orig_ptr still valid so you can clean up
    }
    else
    {
        // Only overwrite orig_ptr once you know the call was successful
        orig_ptr = tmp_ptr;
    }
    

    You need to use tmp_ptr so that if realloc fails, you don't lose the original pointer.

提交回复
热议问题