【发布时间】:2020-10-18 09:02:43
【问题描述】:
我是 C 的新手,我正在尝试创建一个在线杂货店,我可以在其中向商店添加商品并打印每个产品的详细信息,例如名称、库存数量、价格等。
我在将产品添加到产品集合数组并打印时遇到问题。我最大的问题是 main.c 似乎几乎无法识别 defs.h 中声明的每个变量,即使我在文件顶部使用了 include 标记。我也不确定我的 addProd() 函数是否有意义,并希望有人可以验证?
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "defs.h"
int main(){
InventoryType store;
store.storeName = "Walmart";
ProductCollectionType p;
p.numProd = 0;
addProd(&p, 1001, "Grape juice", 12.5);
addProd(&p, 1002, "Pepsi", 4.3);
addProd(&p, 1003, "Apples", 34.0);
int choice;
printf("(1) Print inventory");
printf("(0) Exit");
printf(" ");
printf("Please enter your choice: ");
scanf("%d", choice);
if(choice == 1){
store->printInventory(p)
}
return 0;
}
void printInventory(ProductCollectionType* productArray){
int i;
for(int i = 0; i < numProd; ++i) {
printf("The BLANK store");
printf("-- Product #%d, %s, %d units, $ %.2f", productArray[i].id, productArray[i]->name, productArray[i].numUnits, productArray[i].price);
}
}
int addProd(ProductCollectionType* productArray, int givenId, char givenName, int givenUnits, float givenPrice){
for(i = 0; i < numProd; ++i){
productArray[i].id = givenId;
productArray[i].name = givenName;
productArray[i].numUnits = givenUnits;
productArray[i].price = givenPrice;
}
}
defs.h
#define MAX_NAME 40
#define MAX_PROD 20
#define MAX_UNITS 15
typedef struct{
int id;
char *name;
int numUnits;
float price;
}ProductType;
typedef struct {
ProductType* products[MAX_UNITS];
int numProd;
int nextId;
}ProductCollectionType;
typedef struct{
char *storeName;
ProductCollectionType* productArray[MAX_PROD];
}InventoryType;
【问题讨论】:
-
这只是一个代码转储。请准确指出编译(或运行时)错误在哪里。
-
顺便说一句,这些不是在你的头文件中声明的实际变量(这很好,因为你应该避免这样做)。
-
基本上在我尝试使用该变量的每个函数中。例如,第一个错误出现在 print 函数中,它说 numProd 未声明。当我尝试打印产品的某些详细信息时也是如此
-
嗯,那是因为
numProd确实没有在任何地方声明(即使在你的头文件中,顺便说一句)。