在结构数组中的struct中为数组指定const数组的NULL指针

时间:2014-10-09 10:06:50

标签: c arrays pointers struct

我的结构如下:

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

我制作了这些结构的数组:

struct menu gl_menlist[20];  // all menus

此处的作业失败:

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

错误是:

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

我意识到我的IDE实际上是使用c ++编译器来构建可执行文件。所以我用C ++标记它,而我的所有代码都只是C语言。 如果我将空括号添加到fixtexts,结果是类似的。

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

目前我不知道......

2 个答案:

答案 0 :(得分:1)

你说这实际上是C而不是C ++ ..

有两种选择。

1)memset

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

2)将数组包装在另一个结构中并使用编译器生成结构副本:

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;

在第二种情况下,编译器可能会生成块移动指令,但通常memset也会得到很好的优化。在第二种情况下,您必须将displaystring_fixed[i]的所有访问权限更改为displaystring_fixed.a[i]

答案 1 :(得分:0)

您可能需要menu的构造函数,类似于(并使用nullptr,而不是NULL):

struct menu {
    menu() : fixtexts{nullptr, nullptr, nullptr, nullptr, nullptr} ...
    ...
相关问题