0

我有一个指向结构的指针数组:

item** items = NULL;

这些是我为分配和打印数组而编写的函数:

void allocateItems(item** items, int numItems) {
    items =malloc(numItems*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;
    }
}

void printItems(item** items, int numItems) {
    for (int i = 0; i < numItems; i++) {
        printf("%d : %d\n", items[i]->data, items[i]->data2);
    }
}

但是当我尝试打印该结构数组时,我遇到了分段错误。有人可以告诉我错误在哪里吗?

4

1 回答 1

6

这只是为 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);
}
于 2013-04-09T11:02:14.623 回答