简体   繁体   中英

How to declare a structure variable IN THE MAIN FUNCTION in the case of structure within a structure? Why does this code generate error?

Every time I try to write something like this, I get 2 errors saying-

  • 'struct Outer' has no member named 'i2'
  • 'struct Outer' has no member named 'i2'

    Both of these occur when using i2 in printf and scanf.

    struct Outer
    {
     int val1;
     struct Inner
     {
      int val2;
     };
    };

    int main()
    {
     struct Outer o1;
     struct Inner i2;

     printf("-----To access outer structure-----\n");
     printf("Input for val1\n");
     scanf("%d",&o1.val1);

     printf(----To access inner structure----\n);
     printf("Input for val2\n");
     scanf("%d",&o1.i2.val2); //generates error

     printf("Output for outer structure is %d\n",o1.val1);
     printf("Output for inner structure is %d\n",o1.i2.val2);//generates error
     return 0;
    }

The inner struct is only a definition of a struct. You need to declare a member of that type in the outer class.

struct Outer
{
    struct Inner
    {
        int val2;
    }; // We have defined a struct here

    int val1;
    struct Inner i2; // We have declared a member of that struct type here
};

Now you only define the outer class on your main function:

int main()
{
    struct Outer o1;

    ...

Note that there's no actual need to declare the Inner struct inside the declaration of the Outer struct. They can be totally separate.

Define the structs separately (there is no concept of embedded structs in C)

struct Inner { int val2; };
struct Outer { int val1; struct Inner x; };

Then use an object of the struct Outer type

int main(void) {
    struct Outer in1, in3;
    struct Inner in2;

    in1.val1 = -1;
    in1.x.val2 = -42;

    in2.val2 = 42;

    in3.x = in2;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM