如何访问按值传递给函数的结构数组中的成员?

问题描述:

#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中生成。

+0

貌似的'结构Item'的定义是不存在的。它是在这个文件还是这个文件包含的文件? –

+0

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

+0

您需要在其使用的任何文件中具有结构定义。如果它在多个.c文件中使用,则应将该定义放在.h文件中,并让.c文件包含它。 –

我不知道你怎么称呼你的功能。下面的程序工作没有错误或警告:

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   
=========================================