【问题标题】:What's wrong with my array of pointers to arrays of pointers to structs?我的指向结构指针数组的指针数组有什么问题?
【发布时间】:2014-10-10 18:27:46
【问题描述】:

一个简短的解释,我想做的事情:我想构建一个由结构表示的数据元素的分层树。这些元素应该是双重链接的,所以我可以走路。我不想使用动态分配,因为树的结构在运行时不会改变。

struct menu {
  uint8_t type;  // typ des Menüpunkts
  struct menu * parent; // Pointer auf den übergeordneten MP
  struct menu *(*children)[]; // Pointer auf untergeordnete MP
  };  

struct menu *(*menll[5])[]; // auxillary array

struct menu gl_menlist[5]=
{
  {0,0,menll[0]}, 
  {0,0,menll[1]},
  {0,0,menll[2]},
  {0,0,menll[3]},
  {0,0,menll[4]}
};

struct menu * rxakvt01[]= {&gl_menlist[3], &gl_menlist[4]}; 

menll[0]=&rxakvt01;  

代码在最后一行失败并显示此错误消息:

In file included from Dis0_10.ino:6: var/folders/jl/nv1qvh6n569cxq9xxfd6dx980000gn/T/build753942546562757431.tmp/initialisation.h:71: error: expected constructor, destructor, or type conversion before '=' token

将变量和数组的初始化移动到函数代码后,我收到一条新的错误消息;不过更有意义:

/[path_truncated]/initialisation.cpp: In function 'void shit()':
/[path_truncated]/initialisation.cpp:46: error: cannot convert 'menu* (*)[2]' to 'menu* (*)[]' in assignment

【问题讨论】:

  • 这是我见过的第一个涉及构造函数和析构函数的 C 编译器错误。确定这不是 C++?
  • 哇,那是什么:struct menu *(*menll[5])[];
  • 好的。将标签更改为 c++
  • 使用一些 typedef 使其可读性可能很好。
  • 您到底想要达到什么目的?你有一些你想要模型的菜单层次结构?

标签: c++ arrays pointers tree


【解决方案1】:

很可能,无法将menu *(*)[2] 转换为menu *(*)[] 是编译器的缺陷。

如果您的子菜单的大小不需要是动态的,那么只需声明

struct menu *(*children)[2];

struct menu *(*menll[5])[2];

你应该没事的。

如果您需要动态菜单大小,则需要在某个时候知道子菜单的长度,而这是编译器不会为您派生的,因此建议使用某种标记来指示子菜单。

我在这里发现了另一件可能不是您想要的东西。 gl_menlist 的定义包含 menll 在定义时的值,以后的赋值不会改变它。以下是应该起作用的:

struct menu {
    uint8_t type;  // typ des Menüpunkts
    struct menu * parent; // Pointer auf den übergeordneten MP
    struct menu ***children; // Pointer auf untergeordnete MP
};

struct menu *(*menll[5]);

struct menu gl_menlist[5] =
{
    { 0, 0, &menll[0] },
    { 0, 0, &menll[1] },
    { 0, 0, &menll[2] },
    { 0, 0, &menll[3] },
    { 0, 0, &menll[4] }
};

struct menu *rxakvt01[] = { &gl_menlist[2], 0 };
struct menu *rxakvt02[] = { &gl_menlist[3], &gl_menlist[4], 0 };

menll[0] = rxakvt01;
menll[1] = rxakvt02;

【讨论】:

  • 由于子菜单的数量因菜单而异,我需要动态菜单大小。我做了一个类型转换:menll[0]=(menu* (*)[])&rxakvt01;,它似乎可以工作(我还有其他错误要先解决),但这不是一个好的编程习惯,不是吗?您发现的第二件事是真正的表演终结者。谢谢。
猜你喜欢
  • 2017-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 2016-06-20
相关资源
最近更新 更多