【问题标题】:How can I access members in an array of structures that I passed into a function by value?如何访问按值传递给函数的结构数组中的成员?
【发布时间】:2017-03-19 13:16:39
【问题描述】:
#include <stdio.h>
#include "InventoryManager.h"

void displayInventory(const struct Item items[], const int size)
{
printf("\n\n");
printf("Inventory\n");
printf("=========================================\n");
printf("Sku         Price       Quanity\n");
int index = 0;
for (index = 0; index < size; index++)
{
    printf("%-10.0d  %-10.2f  %-10d\n", items[index].sku, items[index].price, items[index].quantity);
}
printf("=========================================\n");
}

当我尝试访问数组中的结构值时,“项目”下出现红色下划线。

我有 3 个文件,inventoryManger.h、inventoryManager.c、shopping_lab_2.c ...名为 Item 的结构是在 shopping_lab_2.c 中创建的,而您在堆栈溢出中看到的函数是在 inventoryManager.c 中创建的。

【问题讨论】:

  • 看起来struct Item 的定义不存在。是在这个文件中还是这个文件包含的文件中?
  • 我有 3 个文件,inventoryManger.h、inventoryManager.c、shopping_lab_2.c ...名为 Item 的结构是在 shopping_lab_2.c 中创建的,您在堆栈溢出时看到的函数是在库存管理器.c.
  • 您需要在使用它的任何文件中提供结构定义。如果它在多个 .c 文件中使用,则应将定义放在 .h 文件中,并让 .c 文件包含它。

标签: c arrays function structure pass-by-value


【解决方案1】:

我不确定你如何调用你的函数。下面的程序可以正常工作,没有错误或警告:

struct Item{
 int sku;
 float price;
 int quantity; 
};  

void displayInventory(const struct Item items[], const int size)
{
printf("\n\n");
printf("Inventory\n");
printf("=========================================\n");
printf("Sku         Price       Quanity\n");
int index = 0;
for (index = 0; index < size; index++)
{
   printf("%-10.0d  %-10.2f  %-10d\n", items[index].sku, items[index].price,    items[index].quantity);
}
printf("=========================================\n");
}

int main()
{
 Item items[2] = {1, 1.1, 10, 2, 2.2, 20 }; // initialization
 displayInventory(items, 2);
 return 0;
}

输出:

Inventory
=========================================
Sku         Price       Quanity
1           1.10        10        
2           2.20        20        
=========================================

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-12
    • 2020-02-16
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 2021-03-03
    相关资源
    最近更新 更多