Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

struct fruits fruits1 [2] = {
    {banana,&banana[1],&banana[2]},
    {apple,&apple[1],&apple[2]},
};

but is there a better way to do it?

>Solution :

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},
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading