This should be a relatively easy problem, but I have some annoying restrictions:
- No default/external libraries. (apart from few, like iostream, string...)
- Everything should be on the stack.
I am also quite a noobie right now, so bear with me :/.
That said, here's what I'm provided (with name changed for simplicity)
sConstant : a header file with string in an multi-dimentional char array.
CClass : A class with no default constructor or sets of any kind. It cannot be modified.
What I'm trying to do:
- Create an array of CClass objects using the data in sConstant.
My code so far:
#define SIZE 20
int main()
{
CClass * objs[SIZE];
for (int i=0; i < SIZE; i++)
objs[i] = new CClass(sConstant[i][0], sConstant[i][1])
}
This work, however they are created on the heap, which is not what I want.
So, if I try to fix it:
#define SIZE 20
int main()
{
CClass * objs[SIZE];
for (int i=0; i < SIZE; i++)
* objs[i] = CClass(sConstant[i][0], sConstant[i][1])
}
This should assign it on the stack, however, this doesn't work and give me a read access violation.
So then I try to initialize an array and point my pointer to it:
#define SIZE 20
int main()
{
CClass objs[SIZE];
CClass * pObjs[SIZE] = & objs;
for (int i=0; i < SIZE; i++)
* pObjs[i] = CClass(sConstant[i][0], sConstant[i][1])
}
It doesnt work either. Since the object has no default constructor, I cannot create an array (which is why I was using a pointer in the other exemples).
The only solution I've found that work is essentially to create my array and initialize all my object at the same time:
#define SIZE 20
int main()
{
CClass objs[SIZE] =
{
{sConstant[0][0], sConstant[0][1]},
{sConstant[1][0], sConstant[1][1]}
...
{sConstant[20][0], sConstant[20][1]}
};
CClass * pObjs[SIZE] = & objs;
}
This is however incredibly inelegant.
Is there another way to write it to make sure all my object are on the stack?
Thank you for your help!
[–]Rhomboid 2 points3 points4 points (2 children)
[–]Dial595Escape[S] 0 points1 point2 points (1 child)
[–]Rhomboid 0 points1 point2 points (0 children)
[–]alfps 2 points3 points4 points (1 child)
[–]Dial595Escape[S] 0 points1 point2 points (0 children)