Cでは、realloc内にreallocを含めることができますか?たとえば、両方をmallocし、両方を再割り当てする必要がある場合の構造体内の構造体。はいの場合、誰かが簡単な例を提供できますか?前もって感謝します。
1 に答える
6
あなたの質問はひどく明確ではありませんが...
はい、特定の動的に割り当てられた構造体(たとえば、構造体の配列)自体に、割り当てられたデータ(割り当てられた構造体の他のさまざまな配列など)へのポインターを含めることができ、さまざまな部分を個別に再割り当てできます。
ただし、realloc()
構造の1つを再割り当てしている間は、システムはあなたを呼び出しません。さまざまなサイズ変更操作を個別にプログラムする必要があります。
ネストされたデータ構造の例:
struct line { char *info; size_t length; };
struct section { size_t num_lines; struct line *lines; };
セクションの配列を割り当て、必要に応じてその配列を再割り当てできます。各セクションには行の配列が含まれており、これらの行の配列のそれぞれを個別に再割り当てすることもできます。
したがって:
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 = §ions[num_sections++]; // Newly available section
section->num_lines = 0;
section->lines = 0;
return section;
(私はC99を想定しています-必要な場所に変数宣言があります。)
同様のプロセスがセクション内の行の配列に適用されますが、セクション構造には、割り当てられた行の数と実際に使用されている行の数の個別の値がありません。もちろん、各行には文字列用に独自に割り当てられたメモリがあります...
于 2010-11-15T05:14:13.617 に答える