Home > database >  How to nest structures?
How to nest structures?

Time:05-16

typedef struct{
    char name_cake[10];
    char code_cake[10];
    int stock_cake;
    char about_cake[10];
    char cake_taste[10];
}order;

typedef struct{

    char name_cake[10];
    char code_cake[10];
    int stock_cake;
    char about_cake[10];
    char cake_taste[10];
}cake;

how to the contents of typedef struct become one? and I can invoke the command with information.order.name_cake
information.cake.name_cake
for simply and not waste of words, thank

CodePudding user response:

I would recommend to use the same struct for cake and order, there is no polymorphism in c

CodePudding user response:

To access them in the way you like:

    #include <stdio.h>

    typedef struct{
        char name_cake[10];
        char code_cake[10];
        int stock_cake;
        char about_cake[10];
        char cake_taste[10];
    }order;

    typedef struct{
        char name_cake[10];
        char code_cake[10];
        int stock_cake;
        char about_cake[10];
        char cake_taste[10];
    }cake;

    typedef struct {
        union {
            order the_order;
            cake the_cake;
        }; // anonymous union
    }information;

    int main() {
        order an_order = {"cakename", "code", 0, "about", "taste"};

        information info = *((information*)&an_order);

        printf("From order: %s\n", info.the_order.name_cake);
        printf("From cake: %s\n", info.the_cake.name_cake);

        return 0;
    }
$ gcc -Wall ordercake.c
$ ./a.out              
From order: cakename
From cake: cakename
$ 

In general you want to do object-oriented programming in C. Therefore, take a look at: How can I simulate OO-style polymorphism in C? (There is even a free book as pdf linked on how to do it.)

And now an example for a struct in a struct:

    #include <stdio.h>

    typedef struct{
        char name_cake[10];
        char code_cake[10];
    }cake;

    typedef struct{
        cake the_cake; // the common part
        char cake_extension[10]; // the new part, order is important
    }extended_cake;

    int main() {
        extended_cake an_extended_cake = {{"cakename", "code"}, "extension"};
        // now treat it as a cake
        cake *a_normal_cake = (cake *)&an_extended_cake;
        printf("From cake: %s\n", a_normal_cake->name_cake);
        return 0;
    }
$ gcc -Wall ordercake.c
$ ./a.out
From cake: cakename
$ 

CodePudding user response:

#include<stdio.h>
#include<string.h>
struct sports
{
  char name[40];
  int age;
/*nested structure*/
  struct medicaltests
  {
    char isFit[1];
  } med;/*nested object*/
};
int
main ()
{

  struct sports sportobj;/*Declare object*/
  strcpy (sportobj.name, "venkateshwar krishnan");
  sportobj.age = 40;
  strcpy (sportobj.med.isFit, "Y");

  printf ("name of sportsman%s\n", sportobj.name);
  printf ("IsFit %s", sportobj.med.isFit);
  return 0;
}
  • Related