confused about pointer/reference

Started by
3 comments, last by pulpfist 16 years, 1 month ago
Alright. I'm trying to pass my SDL_Surface* screen, by reference/pointer to a function, in order to initialize the screen object. However, it seems I'm not doing it correctly, as i get 2 different addresses when i send them to cout. Heres the code:
[source langg = "cpp"]
Engine::Engine(const SDL_Surface *screen, int width, int height)
{
 //init screen
 cout << &(*screen) << endl;
}

int main()
{
 SDL_Surface* screen;
 GameEngine = new Engine(screen,640,480);
 
 cout << &screen << endl;

return 0;
} 


yields two different addresses. I have always thought passing by pointer/reference was the same, except you should pass variables by pointers if they may not exist..
•°*”˜˜”*°•.˜”*°•..•°*”˜.•°*”˜˜”*°•..•°*”˜˜”*°•.˜”*°•.˜”*°•. Mads .•°*”˜.•°*”˜.•°*”˜˜”*°•.˜”*°•..•°*”˜.•°*”˜.•°*”˜ ˜”*°•.˜”*°•.˜”*°•..•°*”˜I am going to live forever... or die trying!
Advertisement
The initialization process changes the pointer. Since the pointer was passed by value, the changes are not propagated to the caller function.
Ahh yes. Thanks, i fixed it now :). <3
•°*”˜˜”*°•.˜”*°•..•°*”˜.•°*”˜˜”*°•..•°*”˜˜”*°•.˜”*°•.˜”*°•. Mads .•°*”˜.•°*”˜.•°*”˜˜”*°•.˜”*°•..•°*”˜.•°*”˜.•°*”˜ ˜”*°•.˜”*°•.˜”*°•..•°*”˜I am going to live forever... or die trying!
You need to use a double pointer (a pointer to a pointer). Like this:

void init( SDL_Surface** s ) {  SDL_Init(SDL_INIT_VIDEO);  *s = SDL_SetVideoMode( 640, 480, SDL_WHATEVER );}int main( int argc, char* argv[] ) {  SDL_Surface* screen;  init(&screen);  //...}


You have bigger problems though, and you need to touch up on your pointer syntax. In the Engine constructor, you say &(*screen). That's taking the address of a dereferenced pointer. That's the same (in C) as using the pointer's value. On the other hand, in main you're using &screen. This is taking the address of a variable that holds the address of an SDL_Surface. This will be the address of the screen variable itself, which is completely unrelated to what it points to. What you want to say both times is this:

cout << screen << endl;


You're getting two values because:
* You didn't pass a pointer to the pointer you wanted to write to, you passed a copy of it on the stack. This copy will be lost when it goes out of scope at the end of the constructor.
* You printed two different addresses. First, you printed the pointee of the copy of screen, then you printed the address of a pointer variable on the stack.
If you add & to the screen parameter (passing the pointer by reference), the rest of the code should work as it is, except for what UziMonkey said.

Engine::Engine(SDL_Surface* &screen, int width, int height){ //init screen cout << screen << endl;}int main(){ SDL_Surface* screen; GameEngine = new Engine(screen, 640, 480);  cout << screen << endl; return 0;} 

This topic is closed to new replies.

Advertisement