'nested structure array in c
how do I place an array of structures inside another structure to be able to access them all?
struct fruit {
float price;
int supplyId;
int deliveryTime;
};
struct fruits {
struct fruit *item[3];
};
struct fruit banana [3] = {
{1.35, 17, 5},
{1.27, 3, 3},
{2.00, 13, 1},
};
struct fruit apple [3] = {
{2.15, 11, 5},
{1.90, 2, 7},
{1.00, 7, 12},
};
struct fruits fruits1 [2] = {
{banana},
{apple},
};
int main()
{
printf("%f",fruits1[0].item[0]->price);
return 0;
}
in this example, I first price in banana structure, but how do I get 2nd?
I can do it like this:
struct fruits fruits1 [2] = {
{banana,&banana[1],&banana[2]},
{apple,&apple[1],&apple[2]},
};
but is there a better way to do it?
Solution 1:[1]
in this example, I first price in banana structure, but how do I get 2nd?
You can use the subscirpt operator to access siblings of the pointed element:
printf("%f", fruits1[0].item[0][1].price);
It's somewhat unclear, why you have an array of 3 pointers:
struct fruits { struct fruit *item[3]; };
But you only initialise one of the pointers (rest will be null):
struct fruits fruits1 [2] = { {banana},
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
