【发布时间】:2020-10-19 00:13:35
【问题描述】:
我是 C 的新手,我正在创建一个在线商店来管理其库存中的一堆产品。我在打印所有产品时遇到问题。当用户输入 '1' 应该遍历 productCollection 中的所有元素并打印出每个 Product 对象时,它什么也不打印。
我认为这是因为 numberOfProducts 始终为 0,即使我在 addProduct() 中对其进行了迭代。尽管我将迭代器放在哪里,但当我打印 numberOfProducts 时,它总是打印 0。我想知道为什么?
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "defs.h"
void printInventory(ProductCollectionType*);
int addProduct(ProductCollectionType*, int, char*, int, float);
int main(){
InventoryType store;
store.storeName = "Walmart";
ProductCollectionType p;
p.numberOfProducts = 0;
addProduct(&p, 1001, "Grape juice", 20, 12.5);
addProduct(&p, 1002, "Apple juice", 30, 4.3);
int choice;
printf("(1) Print inventory \n");
printf("\n");
printf("Enter choice: ");
scanf("%d", &choice);
printf("%d \n", p.numberOfProducts);
if(choice == 1){
printInventory(&p);
}
return 0;
}
【问题讨论】:
-
在
addProduct中,for(i = 0; i < productCollection->numberOfProducts; ++i)不正确。当然,那个循环永远不会运行。productCollection->numberOfProducts从 0 开始,并且永远不能递增,因为循环永远不会运行。你不需要任何循环。直接跳转到你要添加的索引即可。确保它不会溢出数组。 -
编译时,始终启用警告,然后修复这些警告。 (对于
gcc,至少使用:-Wall -Wextra -Wconversion -pedantic -std=gnu11)注意:其他编译器使用不同的选项来产生相同的结果。函数:addProduct()导致消息:untitled1.c:79:1: warning: control reaches end of non-void function [-Wreturn-type]这不是唯一的问题!