[SDL] SDL_Rect array

Started by
4 comments, last by DuckerDuck 11 years, 10 months ago
Hello,
At the moment i'm trying implement plaforms in my 2d platformer. I want to store the platform data in an array of SDL_Rects. This is what I have:

In my header:

private:
SDL_Rect rPlatformArray[20];//maximum platforms in a level is 20 (for now)


This is how I change the array data:


if (type == 4){
rPlatformArray[NumberOfPlatforms].x = x;
rPlatformArray[NumberOfPlatforms].y = y;
rPlatformArray[NumberOfPlatforms].h = h;
rPlatformArray[NumberOfPlatforms].w = w;
NumberOfPlatforms++;
}


And for rendering:


for (int i = 0; i <= NumberOfPlatforms;i++){
SDL_FillRect(screen,&rPlatformArray,0xFFFFFF);
}


The problem seems to occur when I try to run the second code block.
There are no compile errors, only as soon as the game starts it crashes.


Can you help me?
Thanks,
DuckerDuck
Advertisement

for (int i = 0; i <= NumberOfPlatforms;i++){

What is the value of NumberOfPlatforms? Why don't you use the same constant to specify the size of the array? Doing so will avoid bugs when resizing the array later on. If you're using C++ it's even better to use a container like std::vector.

I can't be sure what the problem is without knowing the value of NumberOfPlatforms, but it's most likely an out of bounds array access. Try to figure out why.

Also, have you ever used a debugger? It allows you to step through your code while the program is running, so you can see when and why it's crashing.
If number of platforms is 20 and you are looping over i<=NumberOfPlatforms then the last element is 21st out of 20, because you are looping over 0, 1, ..., 20 and that's 21 elements. So it's likely out of bounds as already mentioned.

If number of platforms is 20 and you are looping over i<=NumberOfPlatforms then the last element is 21st out of 20, because you are looping over 0, 1, ..., 20 and that's 21 elements. So it's likely out of bounds as already mentioned.


The "NumberOfPlatforms" int starts out as 0, than (with the function of code block 4) the number is increased.

Also, not rendering still makes the game crash.




Also, have you ever used a debugger? It allows you to step through your code while the program is running, so you can see when and why it's crashing.


I have not, but setting breakpoints doesn't seem to work for me, when debugging the app closes instantly. (Visual Studio 2010 Express)
In that case try to print out NumberOfPlatforms before assigning these. If it's 20 or more then there's your crash:
rPlatformArray[NumberOfPlatforms].x = x;

Also have you tried to view stack-trace with debugger or doesn't it give any good results?
Well, I found the problem. Somehow I got the function of code block 4 in a loop. Making NumberOfPlatforms grow far above 19.
Thanks everybody for the respones,

This topic is closed to new replies.

Advertisement