简体   繁体   English

结构数组元素初始化

[英]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 . 在现代C ++ 11或更高版本中(因为您的问题最初仅被标记为C ++),您具有所谓的聚合初始化 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. PS:您应该掌握一本很好的C ++入门书,以便学习该语言的基础知识。

EDIT 编辑

In C (as you re-tagged your question) and pre C++11, you need an equal sign. 在C(重新标记问题)和C ++ 11之前的版本中,需要等号。 Furthermore, in C the inner braces are not optional: 此外,在C中,内括号不是可选的:

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()
{}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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