Skip to main content
gamedev.net
🔒 Locked

Pointers (quick) question...

Started by Greek89 May 4, 2010 at 2:15 AM 1 replies 850+ views
Original Post
Greek89
Greek89
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
seedy
seedy
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.

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

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.