c - 指针数组指向另一个数组

标签 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 打印库存内容?

最佳答案

你应该分配指针数组:

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

关于c - 指针数组指向另一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22753945/

相关文章:

c - 段错误(核心转储)错误

java - 数组编程 - 检查井字游戏中有 n 个玩家的 nxn 棋盘的赢家

c - 段错误,分配给c中的双指针

c - 如何在没有标准库 (libc) 的情况下打印到控制台 (Linux)

c++ - 链接 : fatal error LNK1181: cannot open input file 'libclamav.lib'

java - 二维数组、方法和变量

arrays - 将 bash 数组传递给 Expect 脚本

函数中的 C++ const 参数

c# - c++/c# 编码结构以获取固定指针

c++ - 包括来自不同目录的头文件的问题[不是路径问题]