简体   繁体   中英

struct array element initialization

how may i init below structure with these values:

struct test_str {
unsigned char Add[6];
unsigned int  d;
unsigned char c;
}my_str;

i tried this but resulted in error:

struct test_str {
unsigned char Add[6];
unsigned int  d;
unsigned char c;
}my_str {.Add[0]=0x11,.Add[0]=0x22,.Add[0]=0x33,
         .Add[0]=0x44,.Add[0]=0x55,.Add[0]=0x66,
         .d=0xffe,.c=10};

In modern C++11 or later (as your question was originally tagged C++ only) you have what is called aggregate initialization . It works like this:

struct test_str {
    unsigned char Add[6];
    unsigned int  d;
    unsigned char c;
} my_str { {0x11,  0x22, 0x33, 0x44, 0x55, 0x66},
            0xffe, 
            10
         };

int main()
{}

Live on Coliru

The inner pair of braces is not really necessary, but I prefer it for the sake of clarity.

PS: you should get your hands on a good introductory C++ book so you learn the basics of the language.

EDIT

In C (as you re-tagged your question) and pre C++11, you need an equal sign. Furthermore, in C the inner braces are not optional:

struct test_str {
    unsigned char Add[6];
    unsigned int  d;
    unsigned char c;
} my_str = { {0x11,  0x22, 0x33, 0x44, 0x55, 0x66},
             0xffe, 
             10
           };

int main()
{}

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