c++中嵌套二维结构数组的初始化



在C/c++中,我想对嵌套的二维结构数组进行操作,但未能正确初始化它。结构体meta中的指针应该指向一个二维结构体数组,因此在一个结构体中嵌套一个二维结构体数组。这是我的代码。

#include <iostream>

struct tabparams
{
size_t numrows{ 1 };
size_t numcols{ 1 };
};
struct meta
{
std::string content{};
meta **p { nullptr };
tabparams parameter;
};
void Print(meta **a, tabparams par)
{
for (size_t rowindex = 0; rowindex < par.numrows; rowindex++)
{
for (size_t columnindex = 0; columnindex < par.numcols; columnindex++)
{
if (a[rowindex][columnindex].p == nullptr)
{
std::cout << a[rowindex][columnindex].content << std::endl;
}
else
{
Print(a[rowindex][columnindex].p, a[rowindex][columnindex].parameter);
}
}
}
}
int main()
{
tabparams nestedarrayparams;
nestedarrayparams.numcols = 2;
nestedarrayparams.numrows = 1;
meta nestedarray[2][2] = {
{{"nestedfoo1",nullptr, NULL},{"nestedbaz1", nullptr, NULL}},
{{"nestedfoo2",nullptr, NULL},{"nestedbaz2", nullptr, NULL}}
};
tabparams rootarrayparams;
rootarrayparams.numcols = 2;
rootarrayparams.numrows = 1;
meta rootarray[2][2] = {
{{"foo1",nullptr, NULL} , {"baz", nullptr, NULL} } ,
{ {"",nullptr, NULL }, {"", nestedarray, nestedarrayparams}}
};
}

我得到的错误是Error C2440 'initializing': cannot convert from 'meta [2][2]' to 'meta **'Error (active) E0144 a value of type "meta (*)[2]" cannot be used to initialize an entity of type "meta **"

我必须改变结构体meta中指针的声明吗?nestedarray如何在根数组中被引用?

PrintFunction应该打印roorarray和nestearray的内容字段?在main中调用Print函数的语法是什么?

有很多方法可以做到这一点-尝试坚持使用2D数组,您可以简单地传递指向第一个元素的指针(而不是指向指针的指针),然后是数组的大小。像这样:https://godbolt.org/z/fc8P16heE

但是我真的认为你最好使用STL,比如std::array,如果这是固定大小的

// alias the type for ease
using metaarray = std::array<std::array<meta,2>,2>;
// Note: array initialiser needs double brackets to init the array within the std::array - bit of an odd STL
metaarray nestedarray {{
{{ {"nestedfoo1",nullptr, 0},  {"nestedbaz1", nullptr, 1}  }},
{{ {"nestedfoo2",nullptr, 10}, {"nestedbaz2", nullptr, 11} }}
}};

现在你可以通过引用传递数组,例如:https://godbolt.org/z/d3h861d3v

最新更新