Reputation: 207
What is the difference between the following pairs of statments?
int i;
doSomethingWith(i);
and
int i;
doSomethingWith(&i);
Upvotes: 1
Views: 98
Reputation: 1831
Upvotes: 0
Reputation: 61970
In C, the & is the address-of operator. So instead of passing a copy of i
like you do in the first call, you pass the address of i
, or &i
, which means the function can modify it directly.
The function will look like this:
void doSomethingWith (int *var);
This means it takes a pointer (something that holds the address) to an integer (in this case, i
). Then, to modify i
directly, the function can do:
*var = 5;
This is the dereferencing operator, which gives you what is actually stored at that address. This call will assign 5 to what is stored at the memory location you pass with &i.
Any C textbook should explain this in great detail when it talks about pointers.
Upvotes: 4