I'm new to C and am creating an online store which manages a bunch of products in its inventory. I'm having trouble printing all my products out. When the user enters '1' which should iterate through all the elements in productCollection and print out each Product object, it prints nothing.
I think it's because the numberOfProducts is always 0 even though I iterate it in addProduct(). Despite where I place the iterator, when I print the numberOfProducts, it always prints 0. I was wondering why?
main.c
Code:
#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;
}
void printInventory(ProductCollectionType* productCollection){
int i;
for(int i = 0; i < productCollection->numberOfProducts; ++i){
printf("Walmart Inventory");
printf("Product #%d, %s, %d units, $ %.2f", productCollection->products[i]->id, productCollection->products[i]->name, productCollection->products[i]->numberOfUnits, productCollection->products[i]->price);
}
}
int addProduct(ProductCollectionType* productCollection, int i, char* n, int u, float p){
for(i = 0; i < productCollection->numberOfProducts; ++i){
productCollection->products[i]->id = i;
productCollection->products[i]->name = n;
productCollection->products[i]->numberOfUnits = u;
productCollection->products[i]->price = p;
productCollection->numberOfProducts++;
}
}
defs.h
Code:
#define MAX_NAME 40
#define MAX_UNITS 15
#define MAX_PROD 15
typedef struct{
int id;
char *name;
int numberOfUnits;
float price;
}ProductType;
typedef struct {
ProductType* products[MAX_UNITS];
int numberOfProducts;
int nextId;
}ProductCollectionType;
typedef struct{
char *storeName;
ProductCollectionType* productCollection[MAX_PROD];
}InventoryType;