I'm a beginning programmer and I've been writing a simple game. Unfortunately in my player class the last part of an integer array and a bool variable have the same address. I'm not sure if this is because I'm using public as opposed to private, but it seems like it shouldn't matter for this. I'm thinking I may be missing something, and I would appreciate any help.
#include <cstdlib>
#include <iostream>
usingnamespace std;
class player
{
public:
int playerloc[1];
bool life;
};
int main()
{
player you;
you.playerloc[0]=0;
you.playerloc[1]=0;
you.life=0;
cout<<"values x "<<you.playerloc[0]<<" y "<<you.playerloc[1]<<" life "<<you.life<<endl;
cout<<"ADDR "<<"loc "<<&you.playerloc[1]<<" life "<<&you.life<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
The problem lies with your understanding of array indexing.
An array of [1] has only ONE index and as the index of an array starts at 0 (zero), then the ONLY VALID index for playerloc is playerloc[0].
You can write playerloc[1] or even playerloc[2000] if you want, but these index values are INVALID and you would be trying to access beyond the end of the array.
This is what is happening with you code above. Playerloc[1] just happens to be where the variable life is located.
I would also like to add that this is just incidental. player::life just happens to come right after player::playerloc, but it should be assumed that this is not so.