Hello there and thanks in advance for any help on the following matter.
Edit: I forgot to add that this is on an embedded system with no access to STL features. My apologies for leaving this very important piece of information out. This is my first time coding in C++ extensively so I forgot to mention the obvious. I came back to add this fact and this question had already received some replies. Thank you all for such a quick response!
I am trying to initialize an array member of a struct that is in turn a public member of a C++ class. The array size is omitted in the struct. Here is an example:
// ClassA.h
Class A
{
public:
struct StructA
{
StructB structs[];
};
struct StructB
{
// stuff
};
ClassA();
//etc
};
// ClassB.h
ClassB: public ClassA
{
public:
StructA structA;
ClassB()
// etc
};
// ClassB.cpp
// What do I do here?
I tried:
StructA ClassB::structA.structs[] = { first, second, third }
without any luck. I'm relatively new to C++ so this one has stumped me. I can add a size to the array member in StructA but I would rather not if there is a legal way to handle this.
Thanks!
Arrays without a size aren't valid C++; they're a feature in C99, where they require some malloc
magic to function. If you try to compile code using this feature with g++ -pedantic
, you'll see that it emits:
$ g++ -Wall -pedantic test.cc
test.cc:5: error: ISO C++ forbids zero-size array 'foo'
I suggest you use std::vector
instead, which has the same function as unsized arrays in C99 but is much safer:
std::vector<StructB> structs;
then add elements with push_back
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With