Home > Software engineering >  nested structure array in c
nested structure array in c

Time:03-16

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?

CodePudding user response:

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},
  •  Tags:  
  • c
  • Related