realloc inside a realloc

风格不统一 提交于 2019-12-12 09:23:23

问题


In C can you have realloc inside realloc? For example, a struct inside a struct when you need to malloc both of them and realloc both of them. If yes can someone please provide a simple example? Thank you in advance.


回答1:


Your question is not dreadfully clear, but...

Yes, a given dynamically allocated structure (for example, an array of structures) can itself contain pointers to allocated data (such as various other arrays of allocated structures), and you can reallocate the various parts independently.

However, the system will not call realloc() for you while you are reallocating one of the structures; you would have to separately program the various resizing operations.

Example nested data structures:

struct line { char *info; size_t length; };

struct section { size_t num_lines; struct line *lines; };

You could allocate an array of sections, and reallocate that array when needed. Each section contains an array of lines, and each of those arrays of lines can be independently reallocated too.


Hence:

size_t num_sections = 0;
size_t max_sections = 0;
struct section *sections = 0;

if (num_sections == max_sections)
{
     size_t new_max = (max_sections + 1) * 2;
     struct section *new_sections;
     if (sections == 0)
         new_sections = malloc(new_max * sizeof(*new_sections));
     else
         new_sections = realloc(sections, new_max * sizeof(*new_sections));
     if (new_sections == 0)
         ...out of memory error...
     sections = new_sections;
     max_sections = new_max;
 }
 struct section *section = &sections[num_sections++];  // Newly available section
 section->num_lines = 0;
 section->lines = 0;
 return section;

(I'm assuming C99 - with variable declarations where I want them.)

A similar process applies for the array of lines within a section, except the section structure doesn't have separate values for the number of allocated lines and the number of lines actually in use. Each line also has its own allocated memory for the string of characters, of course...



来源:https://stackoverflow.com/questions/4181568/realloc-inside-a-realloc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!