Sign in to follow this  
MadsGustaf

confused about pointer/reference

Recommended Posts

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..

Share this post


Link to post
Share on other sites
The initialization process changes the pointer. Since the pointer was passed by value, the changes are not propagated to the caller function.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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;
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this