I am having a problem with vectors in c++. I am new to c++ so keep this in mind please.
So I have the following struct in the begining of my program:
typedef struct grupo
{
float transX, transY, transZ, rotX, rotY, rotZ, rotAngle, scaleX, scaleY, scaleZ;
char **modelos;
struct grupo** grupos;
int nNomes = 0, nGrupos=0;
std::vector<float> vertices;
};
struct grupo *grupo;
And I just start the main like this:
grupo = (struct grupo*)malloc(sizeof(struct grupo));
grupo->modelos = (char **)malloc(sizeof(1));
grupo->grupos = (struct grupo **)malloc(sizeof(struct grupo));
And in the middle of main I am tryting to use this:
grupo->vertices.push_back(x);
But it keeps crashing the program. I am using visual studio, and using debugging mode. I can see that is when pushing X to the vector that crashes (x has a value). I've tried to change the vector to an array of floats. So the problem i can imagine is with the initialization of the vector... Can you help with what am I missing?
Thank you :)
You're using C++, you don't need the "new" or malloc keyword unless for specific reasons. You don't need the typedef for structs.
I'm not sure what your char** is supposed to be, but you can use std::string for strings.
Maybe what you're trying to do is this:
struct Grupo
{
float transX, transY, transZ, rotX, rotY, rotZ, rotAngle, scaleX, scaleY, scaleZ;
std::string modelos;
int nNomes = 0, nGrupos=0;
std::vector<float> vertices;
};
In main:
Grupo grupo;
grupo.vertices.push_back( ... );
Then I would advise you to read a bit more about what is exactly the C++ language and how it's not C.
Since you're using C++; if you want to create a grupo
dynamically, you should use the new
operator, with the constructor:
grupo = new grupo();
malloc
does not properly initialize C++ objects such as std::vector
.
P.S. I am not sure what the grupo->modelos
and grupo->grupos
are supposed to be, but I'd use proper C++ types for them (perhaps modelos
should be std::string
, etc). Additionally, I suspect that you've got one *
too much for both modelos
and grupos
.
C++ does not need the typedef in the declaration.
To properly initialize a structure, you should write a ctor to replace the compiler provided ctor (which generally does nothing).
Something like the following (with just a few attributes):
struct grupo
{
float transX, transY;
// ...
int nNomes;
int nGrupos;
std::vector<float> vertices;
// I prefer initialization list form
grupo() : transX(0.0),
transY(1.0),
// ...
nNomes(0),
nGrupos(0)
// vertices default ctor is ok, creates empty vector
{
// use vertices.push_back(...); to fill vertices
}
};
grupo grupo;
Next you will want to write a more useful ctor, one with parameters to use (instead of the literal constants), such that you could build multiple grupo.
grupo grupo1(1.0, 2.0, 3, 4);
grupo grupo2(3.0, 4.0, 5, 6);
// etc.
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