If I have a struct like below:
typedef struct MyStruct {
char **str;
int num;
} MyStruct;
Is there a way for me to initialize an array of this structures. Perhaps like below:
const MyStruct MY_STRUCTS[] = {
{
{"Hello"},
1
},
{
{"my other string"},
3
},
};
Ultimately I would like to have a constantly declared array of structs inside a C++ class. How can this be done? Is it possible to have a privately declared member that is pre-initialized?
You mean something like this:
// In some headerfile:
// in some .cpp file:
That assumes, however, that you have a
char *str;
, sincechar **str;
requires a secondary variable to take the address off. Or, you could usestd::vector<string>
, and that would solve the problem.Sure, you'd write it like this:
Unless I'm misunderstanding and you actually just want
num
to count the number of elements. Then you should just have:And you can recover the element sizes with
data[0].size()
,data[1].size()
, etc.If everything is determined statically and you just want a compact reference, you still need to provide storage, but everything is virtually the same as in C:
Since the size is
std::distance(std::begin(a0), std::end(a0))
, you could simplify the last part with a macro that just takesa0
as an argument. And instead of handwritingFoo
, you might just usestd::pair<char const **, std::size_t>
.You can use something like
assuming you
struct
's first member is actuallychar const*
rather thanchar**
as you initialization example suggests.