so I have a structure called Shield that has three pointers in it. I need to fill up with data one of this pointers before hand and I need to access this data inside of a constant loop. The problem that I'm having is that whenever I try and access what should be in my pointers my program crashes. This is my structure
struct Shield{
esat::Vec3 *circle;
esat::Vec2 *walls;
bool *isActive;
};
where esat::Vec3 and esat::Vec2 are just structures with floats representing vectors.
I initialize my pointers inside of a function that takes as a parameter an Shield object and fill up such pointer data that I need.
void InitShield(Shield shield){
shield.circle = (esat::Vec3*) malloc((KVertices + 1) * sizeof(esat::Vec3));
shield.walls = (esat::Vec2*) malloc((KVertices + 1) * sizeof(esat::Vec2));
shield.isActive = (bool*) malloc((KVertices + 1) * sizeof(bool));
float angle = 6.28f / KVertices;
for(int i=0; i<KVertices; ++i){
(*(shield.circle + i)).x = cos(angle * i);
(*(shield.circle + i)).y = sin(angle * i);
(*(shield.circle + i)).z = 1.0f;
(*(shield.isActive + i)) = true;
}
}
And then I try and get access to what I supposedly stored in my pointer.
void DrawCircle(esat::Mat3 base, esat::Vec2 *tr_points, esat::Vec3 *circle, bool *checkActive){
CheckShield(first_shield);
for(int i=0; i<KVertices; ++i){
esat::Vec3 points = esat::Mat3TransformVec3(base, (*(circle + i)));
*(tr_points + i) = {points.x, points.y};
}
for(int i=0; i<KVertices; ++i){
if((*(checkActive + i)) == true){
esat::DrawSetStrokeColor(color.r, color.g, color.b);
esat::DrawLine((*(tr_points + i)).x, (*(tr_points + i)).y, (*(tr_points + ((i+1)%KVertices))).x, (*(tr_points + ((i+1)%KVertices))).y);
}
}
}
This is where my program crashes. When I try and access what should be inside my circle pointer the program fails to and crashes. Does anyone know what am I doing wrong? I haven't figured it out yet.
This function accepts an object of the type Shield by value.
void InitShield(Shield shield){
That is the function deals with a copy of the value of the passed argument.
Changing the copy within the function does not influence on the original object.
If you are using C++ then declare the function at least like
void InitShield(Shield &shield){
and use the operator new
instead of calling malloc
directly.
If you are using C then declare the function like
void InitShield(Shield *shield){
Also it is unclear why you are allocating KVertices + 1
objects as for example
shield.circle = (esat::Vec3*) malloc((KVertices + 1) * sizeof(esat::Vec3));
But the following for loop uses only KVertices
iterations.
for(int i=0; i<KVertices; ++i){