Reputation: 11130
I want to declare a struct:
struct myStruct{
myType myVar[mySize];
//...
};
How do I do this, or where do I put this, such that I am allowed to do this when the value of mySize
is known at runtime?
mySize
actually has a default value, but the user can provide a different value through the standard input. This custom size is then passed to a function, where the struct is defined.
But if the struct is inside the function definition, I get an error saying it is not allowed to be variable, and if I put it outside the function (in the header), it complains that mySize
is not defined - of course, it is not passed there by any means.
My guess is that the solution lies in OOP*, but this is not something I have yet studied.
*If this is a false assumption, please tell me so I can remove the tag.
Upvotes: 0
Views: 48
Reputation: 545588
A C array cannot have a dynamic size in C++ as a class member. However, C++ has a class which provides just that – std::vector
.
This gives us:
struct myStruct {
std::vector<myType> myVar;
myStruct(std::size_t size = default_size)
: myVar(size) {}
};
Take home message: Familiarise yourself with the C++ standard library, working without a solid knowledge of it is pretty much impossible in C++.
Upvotes: 1
Reputation: 3049
You could use a vector
#include <vector>
struct myStruct
{
public:
// this is your array
std::vector<myType> myVar;
// this is the default constructor
// this tells that the user will be passing a number
myStruct(int const &mySize)
{
myVar.resize(mySize);
}
};
That way in the main
int main()
{
myStruct example(10);
return 0;
}
This way, you don't have to worry about memory management.
myStruct
is an object.
There are two types of memories, stack and heap, you should learn about them if you want to get into pointers and memory management. I am going to tell you how to do this with pointers, but I don't recommend you to go down this path so soon
struct myStruct
{
public:
// this is your array
myType *myVar;
// this is the default constructor
// this tells that the user will be passing a number
myStruct(int const &mySize)
{
myVar = new myVar[mySize];
}
// this is your default destructor
~myStruct()
{
delete[] myVar;
}
};
But myVar becomes a pointer and it is handled differently than a vector.
Vector is part of the C++ Standard Library. If this is not for a homework I suggest you use it.
Upvotes: 1