私は動的配列を持っています。各要素は、とりわけ動的に割り当てられた文字配列を含む構造体です。
アレイのサイズを変更すると、古いアレイより約50%大きい新しいアレイを作成し、古いアレイのデータを新しいアレイにコピーし、古いアレイを削除します。ここで
はコードです:
構造体の動的配列のサイズを変更するときに、構造体に動的メモリをコピーする必要がありますか?
typedef struct Thing
{
char* str; /* dynamic memory */
int num;
int other_data;
} thing;
typedef struct ThingStream
{
thing* things; /* dynamic memory */
int capacity;
int size;
} thing_stream;
void resize_thing_stream(thing_stream* ts)
{
int new_capacity;
thing* new_things;
int i;
new_capacity = ts->capacity + ts->capacity/2;
new_things = malloc(new_capacity * sizeof(thing));
for(i = 0; i < ts->size; i++)
{
new_things[i] = ts->things[i];
/* here is where I would copy the str data */
}
free(ts->things);
ts->things = new_things;
ts->capacity = new_capacity;
}
は、私はちょうどstr
が新しい配列になることを期待することができ、または私は新しい配列にstr
データをコピーする必要がありますか?
は単に 'realloc'を使用します。 – BLUEPIXY
文字列のメモリをコピーする必要はありません。各要素は、割り当てられたメモリへのポインタを保持しているため、再割り当てする必要はありません。だから答えは「はい」です。新しい配列に 'str'があると期待できます。 – ProXicT
ありがとう!ダイナミックメモリを含むダイナミックメモリを解放するとメモリリークが発生する可能性があると思われるその他の質問と回答がありました。 – biscuit