problem with memory addresses

Started by
1 comment, last by krokko 16 years, 8 months ago
Hi everyone, I'm having quite a bit of trouble with arrays and variables declared after them.
 class Block
{
      private:
              
      SDL_Rect squares[3];
      
      blockType kind; 
...
The problem is that the 'kind' variable gets the same memory address as the last element in the array I declared ( actually, the same address as the first member variable in the last element ), which really messes everything up. It's been spooking me for a really long time and I've redone loads of stuff because I couldn't figure out why my variable was changing without being explicitly changed. There must be some kind of way to avoid this, please help! I'd be grateful for any :) Thanks teo
Advertisement
The kind variable doesn't get the same address as the address of the last element of the array.

You're probably going out of bounds of the array, i.e. you're doing something like this:
SDL_Rect squares[3];blockType kind;...squares[0] = something;  // Arrays are 0-based, so this is actually the first element.squares[1] = something;  // The second element..squares[2] = something;  // And the last element.sqaures[3] = something;  // Now, you're trying to access a fourth element of a three-elements array.                         // This usually ends up modifying the variable that comes right after the array,                         // 'kind' in this case.
It's easy to do a mistake like this by iterating over the array using a loop similar to for (int i = 1; i <= 3; ++i) ... -- notice that this loop iterates over elements squares[1] to squares[3].
Thanks I can't believe I overlooked that. I did actually mean for it to be a four element array :D and I've been beating my head over this for 2 days :D

bless you!

This topic is closed to new replies.

Advertisement