指向另一个数组的指针数组

时间:2014-03-31 05:03:01

标签: c arrays pointers

我正在尝试创建一个指向另一个结构数组的指针数组。 但是,我很困惑我是否应该将新数组声明为int或与第一个数组相同的类型,因为它将保留指针。 这就是我到目前为止所做的:

struct inventoryItem
{
    int itemNumber;
    int itemsInStock;
    float cost;
    float retailPrice;

};


int main()
{
    printf("Enter the number of slots needed in the array: ");
    int size;
    scanf("%d", &size);

    //array of items
    struct inventoryItem *inventory; //use pointer to item 
    inventory =(struct inventoryItem *) malloc(sizeof(struct inventoryItem)*size); //create array to store inventoryItem with size 'size'

    //array of index
    //int *indexArray = (int*) malloc(sizeof(int)*size); 
    struct inventoryItem *indexArray; //use pointer to item 
    indexArray =(struct inventoryItem *) malloc(sizeof(struct inventoryItem)*size); //create array to store inventoryItem with size 'size'

    //fill array contents
    for(int i = 0; i < size; i++)
    {
        printf("Enter item %d number: ", i);
        scanf("%d", &inventory[i].itemNumber);

        printf("Enter item %d stock: ", i);
        scanf("%d", &inventory[i].itemsInStock);

        printf("Enter item %d cost: ", i);
        scanf("%f", &inventory[i].cost);

        printf("Enter item %d price: ", i);
        scanf("%f", &inventory[i].retailPrice);
    }

    for(int i = 0; i < size; i++)
    {
        printf("Item %d number: %d\n", i, inventory[i].itemNumber);
        printf("Item %d stock: %d\n", i, inventory[i].itemsInStock);
        printf("Item %d cost: %f\n", i, inventory[i].cost);
        printf("Item %d retail price: %f\n", i, inventory[i].retailPrice);
    }


    //struct inventoryItem *header = inventory;
    //struct inventoryItem *ptr = inventory;
    for(int i = 0; i < size; i++)
    {
        indexArray[i] = &inventory[i]; 
            //problem here, it says "no operator '=' matches these operands"

    }
}

编辑: 现在我创建了数组,如何使用indexArray打印库存内容?

5 个答案:

答案 0 :(得分:2)

你应该分配指针数组:

struct inventoryItem **indexArray;
indexArray = (struct inventoryItem **)malloc(sizeof(struct inventoryItem*)*size);

答案 1 :(得分:1)

将`indexArray'声明为

struct inventoryItem **indexArray;

使用

创建它
indexArray =(struct inventoryItem **) malloc(sizeof(struct inventoryItem *)*size);

并填写

indexArray[i] = &inventory[i]; 

indexArray[i] = inventory + i; 

答案 2 :(得分:1)

为了便于阅读,最好先做一个typedef:

typedef struct inventoryItem Inv;

如果要创建指向struct数组的指针数组,而不是

Inv* indexArray = malloc(sizeof(Inv)*size); 

Inv** indexArray = malloc(sizeof(Inv*)*size);

答案 3 :(得分:0)

struct inventoryItem **inventory; //use pointer to item 
inventory =(struct inventoryItem **) malloc(sizeof(struct inventoryItem*) * size);

答案 4 :(得分:0)

到目前为止,您有两个指针,每个指针指向一个结构数组的第一项。

如果你想要一个T数组,那么你使用T[]表示法,指针与其他类型没有区别。所以

struct inventoryItem *foo[10];
foo[0] = malloc( size * sizeof *foo[0] );

等。在此示例中,inventory替换为foo[0]。你当然可以写struct inventoryItem *inventory = foo[0];

当然,如果在编译时不知道您需要的数组数量,也可以动态分配foo

struct inventoryItem **foo = malloc( 10 * sizeof *foo );