Pointers (quick) question...

Started by
1 comment, last by DevFred 13 years, 11 months ago
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?
peter_jim89@hotmail.com
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.

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.

This topic is closed to new replies.

Advertisement