这只是为 a 分配足够的内存item*
:
items[i]=malloc(sizeof(item*));
它必须为 a 分配内存item
:
items[i]=malloc(sizeof(item));
为了使allocateItems()
调用者可以看到所做的更改,items
必须传入的地址:
allocateItems(&items, 4);
items
必须在函数内取消引用参数类型和方法的更改:
void allocateItems(item*** items, int numItems)
{
*items = malloc(numItem * sizeof(item*));
for (int i = 0; i < numItems; i++)
{
(*items)[i] = malloc(sizeof(item));
(*items)[i]->data = i + 1;
(*items)[i]->data2 = (i + 1) % 2;
}
}
This could be simplified by allocating an array of item
instead of an array of item*
. It would also mean that the list of items
are in a contiguous block of memory instead of being fragmented with the multiple malloc()
for allocating each element in the array:
void allocateItems(item** items, const int numItems)
{
*items = malloc(numItems * sizeof(item));
if (*items)
{
for (int i = 0; i < numItems; i++)
{
(*items)[i].data = i + 1;
(*items)[i].data2 = (i + 1) % 2;
}
}
}
item* items;
allocateItems(&items, 4);
if (items)
{
for (int i = 0; i < 4; i++)
printf("[%d]: (%d, %d)\n",
i,
items[i].data,
items[i].data2);
free(items);
}