c++ - 将结构数组传递给函数。获取指针和表达式错误
问题描述
我正在尝试编写一个显示结构数组的函数(如库存,每个结构都有自己的行)。正如标题所说,我在尝试为此函数编写原型和标头时遇到了一些困难。这是我到目前为止所拥有的:
// 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。你不需要一直把这个词struct
放在struct
.
您有两个名为displayTable
. 您已经声明了一个void displayTable(struct Product inventory[])
接受 s 数组的函数struct Product
。您已经定义了一个完全不同的函数void displayTable(Product* inventory[])
,它接受一个Product*
. Astruct Product
不是Product*
.
解决方案是将您的函数签名更改为void displayTable(Product inventory[])
,并将此确切签名用于前向声明和定义。
推荐阅读
- c - 当我们在 C 中覆盖联合字段时会发生什么?
- java - 使用jsoup解析html表格
- haskell - 有没有办法将这个函数重写为全部?
- python - 使用python检查2个数据帧之间的逗号分隔列值中的部分字符串
- python - 找到句子中的第一个数字单词
- powershell - 需要将时间与字符串分开
- php - .htaccess 在匹配包含 URL 中的单词时调用特定页面
- oracle - 生成从两个日期开始的连续期间(对于一对 ID 和值)
- javascript - 如何给出还剩多少次尝试
- google-bigquery - 在 Java 类中读取 BigQuery 表数据(Pojo)