3

How do you access members of a struct that is defined within another struct?
Suppose we have a struct defined as:

struct FR {
    size_t n;
    struct FR_1{
        unsigned char r;
        unsigned char g;
        unsigned char b;
    };
};

Under visual studio 2015,writing:

    struct FR x;
    x.FR_1.

does not display options for FR_1 members.On the other hand,writing:

struct FR_1 y; Says: Error,incomplete type is not allowed.

How do you deal with this kind of struct?

  • 1
    You define an inner structure, but no member of that type. – Jarod42 May 24 '16 at 21:20
  • 1
    You need to declare it as **FR::FR_1** – cup May 24 '16 at 21:24
  • 1
    You know that's covered in every [decent C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list?lq=1). Maybe you should get one and learn the language. – Rob K May 24 '16 at 21:30

3 Answers3

11

The sample declares the type struct FR_1, not a member of that type. Instead, try:

struct FR {
    size_t n;
    struct FR_1 {
        unsigned char r;
        unsigned char g;
        unsigned char b;
    } fr1;
};

FR x;
x.fr1.r = 0;
AlexD
  • 32,156
  • 3
  • 71
  • 65
5
struct FR {
    size_t n; // < Declaration of member variable
    struct FR_1{ // < Declaration of nested type
        unsigned char r;
        unsigned char g;
        unsigned char b;
    };
    FR_1 fr1; // < Declaration of member variable
};

You need to declare a variable of the type FR_1 in your FR structrure, not only the type itself.

FR fr;
fr.fr1.r = 0;
Teivaz
  • 5,462
  • 4
  • 37
  • 75
0

You need to actually create an instance of the structure. A normal struct declaration follows the form

struct struct-name {
    members
} inst;

So you need to declare it as

struct FR {
    size_t n;

    struct FR_1 {
        unsigned char r;
        unsigned char g;
        unsigned char b;
    } fr1;
};

Now you can write

FR fr;
fr.fr1.r = 255;
. . .
lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75