Access Violation setting rectangle clips

Started by
13 comments, last by nano511 12 years, 8 months ago
Everytime my program gets to the bolded line, i get an access violation error. WHY?



void Player::SetClips()
{
//Set clips for healthbar
for( int i = 0; i < 12; i++ )
{
healthbarClips->x = 0;
healthbarClips->y = 22 * i;
healthbarClips->h = 22;
healthbarClips->w = 374;
}
}
Advertisement
I don't see a bold line, but how is healthbarClips initialized?
SDL_Rect *healthbarClips[11];

i tried making the line bold, but on my screen it just shows the bold code block things.
Did you allocate space for the array beforehand?
by allocate do you mean use 'new'?

If so, then no.
oh, i see it. Your array is of size 11, but your iterating up to 11 (one less than 12), but starting at 0, so you're iterating through 12 numbers. the index of the healthbarClips goes from 0 to 10 (11 numbers), so your final iteration goes out of bounds.

Does that help?
No that doesnt help lol. It stops it on the first loop anyways.
my c++ pointer use is a bit rusty, so someone else may need to confirm this, would nano511 need to do a malloc on the memory address size for this to work for him, to pre-allocate the address space since its a pointer to an array?
Have you tried:

SDL_Rect *healthbarClips = new SDL_Rect[11];


Also, don't forget to call delete[] healthbarClips and not delete healthbarClips.
Try this


void Player::SetClips()
{
//Set clips for healthbar
for( int i = 0; i < 12; i++ )
{
healthbarClips = new SDL_Rect;
healthbarClips->x = 0;
healthbarClips->y = 22 * i;
healthbarClips->h = 22;
healthbarClips->w = 374;
}
}



don't forget to deallocate the memory for preventing memory leaks

This topic is closed to new replies.

Advertisement