Sign in to follow this  
Greek89

Pointers (quick) question...

Recommended Posts

Greek89    100
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
seedy    122
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
DevFred    840
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

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