一个realloc的内部的realloc [英] realloc inside a realloc

查看:142
本文介绍了一个realloc的内部的realloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C可你里面的realloc realloc的?例如,一个结构内部的结构,当你需要的malloc他们两个和realloc他们两个。如果是有人可以请提供一个简单的例子?
谢谢你在前进。

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.

推荐答案

您的问题并不可怕清楚,但...

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.

但是,系统不会叫的realloc()为你,而你是重新分配结构之一;你将不得不单独编程不同的大小调整操作。

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.

例嵌套的数据结构:

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.

因此​​:

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;

(我假设C99 - 与在那里我希望他们变量声明)

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

这篇关于一个realloc的内部的realloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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