简体   繁体   中英

Assigning const array of NULL pointers to array in struct inside array of structs

My struct looks as follows:

struct menu {
    uint8_t type;  
    struct menuentry * parent; 
    struct displaystring * fixtexts[5];  
    // uint8_t ftnum;  
    struct menuentry * children; 
    uint8_t chnum;  
    uint8_t state;  
    uint8_t entry;  
    struct displaystring * selentrystr;  
};  

I make an array of these structs:

struct menu gl_menlist[20];  // all menus

Assignment fails here:

gl_menlist[0].fixtexts={NULL, NULL, NULL, NULL, NULL};

Errors are:

Testdisplayarbstring.ino: In function 'void setup()':
Testdisplayarbstring.ino:209: error: expected primary-expression before '{' token
Testdisplayarbstring.ino:209: error: expected `;' before '{' token

I realised my IDE is actually using a c++ compiler to build the executable. So I tagged it with C++ while all of my code is C only. If I add empty braces to fixtexts, outcome is similar.

Dis0_10.ino: In function 'void setup()':
Dis0_10.ino:209: error: expected primary-expression before ']' token
Dis0_10.ino:209: error: expected primary-expression before '{' token
Dis0_10.ino:209: error: expected `;' before '{' token

I have no clue at the moment...

You say this is actually C and not C++..

There are 2 options.

1) memset

memset(gl_menlist[0].fixtexts, 0, sizeof(gl_menlist[0].fixtexts));

2) Wrap the array in another struct and use compiler generate struct copy:

struct displaystring_fixed {
    displaystring * a[5];
};
struct menu {
    uint8_t type;  
    struct menuentry * parent; 
    struct displaystring_fixed fixtexts;  
    // uint8_t ftnum;  
    struct menuentry * children; 
    uint8_t chnum;  
    uint8_t state;  
    uint8_t entry;  
    struct displaystring * selentrystr;  
};  

static const displaystring_fixed displaystring_fixed_init = {NULL, NULL, NULL, NULL, NULL};

gl_menlist[0].fixtexts = displaystring_fixed_init;

In the second case the compiler may generate block move instructions, though usually memset is well optimized also. Also in second case you then have to change all accesses of displaystring_fixed[i] to displaystring_fixed.a[i] .

You probably want a constructor for menu , something like (and use a nullptr , not NULL ):

struct menu {
    menu() : fixtexts{nullptr, nullptr, nullptr, nullptr, nullptr} ...
    ...

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