首页 > 解决方案 > 将结构数组传递给函数。获取指针和表达式错误

问题描述

我正在尝试编写一个显示结构数组的函数(如库存,每个结构都有自己的行)。正如标题所说,我在尝试为此函数编写原型和标头时遇到了一些困难。这是我到目前为止所拥有的:

// Prototype, before main (where "Product" and "inventory[50]" are declared and initialized)
void displayTable(struct Product inventory[]);

// Calling displayTable in main()
displayTable(inventory[]);


// The function itself
void displayTable(Product* inventory[]) {
    for (int i = 0; i<50; i++) {
        cout << inventory[i].name << " " << inventory[i].inStock << " " << inventory[i].unitPrice << endl;
    }
}

我遇到了一大堆错误。当我调用函数时,第一个在最后一个括号下,我得到“预期的表达式”。我在函数内部的for循环中的每个“库存”下得到“表达式必须是指向完整对象类型的指针”。

标签: c++

解决方案


C++ 不是 C。你不需要一直把这个词struct放在struct.

您有两个名为displayTable. 您已经声明了一个void displayTable(struct Product inventory[])接受 s 数组的函数struct Product。您已经定义了一个完全不同的函数void displayTable(Product* inventory[]),它接受一个Product*. Astruct Product不是Product*.

解决方案是将您的函数签名更改为void displayTable(Product inventory[]),并将此确切签名用于前向声明和定义。


推荐阅读