[英]How do I allocate more space for my array of C structs?
我正在嘗試向我的結構添加10個元素,這個元素已經是malloc,其大小為20,這就是我定義結構的方式:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct st_temp {
char *prod;
};
int main ()
{
struct st_temp **temp_struct;
size_t j;
temp_struct = malloc (sizeof *temp_struct * 20);
for (j = 0; j < 20; j++) {
temp_struct[j] = malloc (sizeof *temp_struct[j]);
temp_struct[j]->prod = "foo";
}
return 0;
}
所以我想到的是重新分配(但是,不知道如何):
temp_struct = (struct st_temp **) realloc (st_temp, 10 * sizeof(struct st_temp*));
然后添加額外的10個元素,
for (j = 0; j < 10; j++)
temp_struct[j]->prod = "some extra values";
我怎么能實現這個目標? 任何幫助表示贊賞!
使用realloc()
,必須提供新大小而不是要添加的字節數。 所以:
temp_struct = (struct st_temp **) realloc (temp_struct, 30 * sizeof(struct st_temp*));
30當然是你原來的20加10多。 如果需要移動內存塊, realloc()
函數負責將原始數據復制到新位置。
然后,添加額外的10個元素就像是(從索引20開始,而不是0):
for (j = 20; j < 30; j++) {
temp_struct[j]->prod = "some extra values";
}
為了避免內存泄漏,我們需要謹慎處理重新分配(稍后會詳細介紹)。 realloc函數:
void *realloc(void *ptr, size_t size)
,where
ptr
=指向原始( malloc
)內存塊的指針,和
size
=內存塊的新大小(以字節為單位)。
realloc
返回動態分配的內存塊的新位置(可能已更改) - 如果重新分配失敗,則返回NULL! 如果它返回NULL,則原始內存保持不變,因此必須始終使用臨時變量作為realloc
的返回值。
一個例子將澄清一點(興趣點:realloc語法類似於malloc的(不需要額外的強制轉換等),並且在realloc之后,你需要像在malloc之后那樣為新對象生成相同的步驟):
struct st_temp **temp_struct;
temp_struct = malloc(20 * sizeof *temp_struct);
if (temp_struct == NULL) { /* handle failed malloc */ }
for (int i = 0; i < 20; ++i) {
temp_struct[i] = malloc(sizeof *temp_struct[i]);
temp_struct[i]->prod = "foo";
}
// We need more space ... remember to use a temporary variable
struct st_temp **tmp;
tmp = realloc(temp_struct, 30 * sizeof *temp_struct);
if (tmp == NULL) {
// handle failed realloc, temp_struct is unchanged
} else {
// everything went ok, update the original pointer (temp_struct)
temp_struct = tmp;
}
for (int i = 20; i < 30; ++i) { // notice the indexing, [20..30)
// NOTICE: the realloc allocated more space for pointers
// we still need to allocate space for each new object
temp_struct[i] = malloc(sizeof *temp_struct[i]);
temp_struct[i]->prod = "bar";
}
// temp_struct now "holds" 30 temp_struct objects
// ...
// and always do remember, in the end
for (int i = 0; i < 30; ++i)
free(temp_struct[i]);
free(temp_struct);
請注意,這不是一個結構數組,而是一個指向結構的指針數組 - 如果你願意的話,甚至是結構數組的數組。 在最后一種情況下,每個子數組的長度為1(因為我們只為一個結構分配空間)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.