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?

3
  • 1
    You define an inner structure, but no member of that type. Commented May 24, 2016 at 21:20
  • 1
    You need to declare it as FR::FR_1 Commented May 24, 2016 at 21:24
  • 1
    You know that's covered in every decent C++ book. Maybe you should get one and learn the language. Commented May 24, 2016 at 21:30

3 Answers 3

12

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;
Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

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;
. . .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.