Jump to content
  • Advertisement
Sign in to follow this  
Greek89

Pointers (quick) question...

This topic is 3115 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Consider this: void function1() { int variable = 5; function2(&variable); } void function2 (int *var) { *(var) = 10; //Function1.variable now is 5 return; } My question is: Instead of using "&variable" and "*var" as parameters, couldnt we just use "variable" and "var"? What is the point of using pointers in a function?

Share this post


Link to post
Share on other sites
Advertisement
If you rewrote the code to

void function1()
{
int variable = 5;
function2(variable);
}


void function2 (int var)
{
var = 10;
return;
}

It would not work , function2 gets passed a copy of the variable which it can alter. It will not alter "variable".

If you are using C++ and not C you can use refernces which would make the code look like

void function2 (int & var)
{
var = 10;
return;
}

This code would change "variable" just like the pointer version.

Share this post


Link to post
Share on other sites
Quote:
Original post by Greek89
Instead of using "&variable" and "*var" as parameters, couldnt we just use "variable" and "var"?

If you did that, then the information "5" would be passed. function2 would have no idea where that 5 came from. There would be no connection to variable. Changes wouldn't be reflected to the caller.

If instead you pass &variable, you pass the information where the variable is stored. Basically, you pass "the variable itself", if you will, thus function2 is able modify it.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!