I have the following code, I am trying to store a market_order struct into my products.buys array
Here are what my structs look like
typedef struct market_order {
char type[5];
int price;
int quantity;
char item[20];
int traderId;
int orderId;
int number_of_orders;
int orderCount;
} MarketOrder;
typedef struct products{
int buy_levels;
int sell_levels;
struct market_order *buys[20];
struct market_order *sells[20];
} Products;
struct products *products;
In my main method, in initalize memory space for my global products ptr. Like this
products = malloc(sizeof(struct products));
I then have another method that adds new elements to my products.buys keeping a counter for how many elements I have added so iteration is easier.
void populate_buy_orders(int traderId, int orderId, char* item, int quantity, int price){
MarketOrder* new_order = malloc(sizeof(struct market_order));
if (new_order == NULL) {
printf("Failed to allocate memory for new order\n");
return;
}
new_order->traderId = traderId;
new_order->orderId = orderId;
new_order->quantity = quantity;
new_order->price = price;
new_order->number_of_orders = 1;
new_order->orderCount = products->buy_levels;
products->buys[products->buy_levels] = new_order;
++products->buy_levels;
}
I get a segmentation fault at this line
products->buys[products->buy_levels] = new_order;
What could be the issue?