[英]Realloc in C for structs containing dynamic array of structs
重新分配項目列表時出現問題。 我試圖將項目添加到testList結構項目中,但是嘗試添加或打印單個ListItems的值時遇到內存地址錯誤。 任何幫助將不勝感激。
struct ListItems
{
int id;
int name;
};
struct testList
{
struct ListItems** items;
int count;
int size;
};
struct Test
{
struct testList* list;
};
void printArray(struct testList* list)
{
for (int i = 0; i < list->count; i++)
{
printf("id=%i, name= %i \n", list->items[i]->id, list->items[i]->name);
fflush(stdout);
}
printf("printing accomplished \n");
fflush(stdout);
}
void growArray(struct testList* list, struct ListItems* item)
{
int size = list->size;
list->items[list->count++] = item;
struct ListItems** user_array = list->items;
//printf("array count %i, array size %i \n", list->count, size);
if (list->size == list->count)
{
struct ListItems* temp = realloc(*user_array, (size * 2) * sizeof (struct ListItems));
if (temp == NULL)
{
printf("it's all falling apart! \n");
}
else
{
*user_array = temp;
list->size = size * 2;
}
}
}
/*
*
*/
int main(int argc, char** argv)
{
struct Test* test = (struct Test*) malloc(sizeof (struct Test));
test->list = (struct testList*) malloc(sizeof (struct testList));
test->list->count = 0;
test->list->size = 1;
test->list->items = (struct ListItems**) malloc(sizeof (struct ListItems*));
for (int i = 0; i < 32; i++)
{
struct ListItems* item = (struct ListItems*) malloc(sizeof (struct ListItems));
item->id = i;
item->name = i;
growArray(test->list, item);
}
printArray(test->list);
for (int j = 0; j < sizeof (test->list->items); j++)
{
free(test->list->items[j]);
}
free(test->list->items);
free(test->list);
free(test);
}
您的growArray()
需要更新list->items
。 在當前代碼中,它將永遠僅指向1元素大小的區域。
編輯:
您的realloc()
分配了sizeof (struct ListItems))
但指針包含指針,而不包含元素。
我會寫:
void growArray(struct testList* list, struct ListItems* item)
{
if (list->size <= list->count) {
size_t new_size = 2 * list->size;
struct ListItems** temp = realloc(list->items, new_size * sizeof temp[0]);
assert(temp);
list->size = new_size;
list->items = temp;
}
list->items[list->count] = item;
++list->count;
}
這樣,您就不需要main()
的初始list->items = malloc(...)
,而是可以分配NULL
。
編輯:
for (int j = 0; j < sizeof (test->list->items); j++)
沒有道理; 您可能想要j < test->list->count
。
問題始於struct testList
的聲明。 指向items
數組的指針應該只有一個*
:
struct testList
{
struct ListItems* items; // Changed from pointer-to-pointer
int count;
int size;
};
這將迫使代碼進行其他一些更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.