Reputation: 104
As C doesn't support pass by reference, when we write functions that make changes to the values of parameters we take pointers as parameters. For example:
void swap(int *ptr1, int *ptr2)
{
int temp;
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
}
When calling this function I can either pass two pointers or pass the variables with the &
operator, like swap(ptr1, ptr2)
or swap(&num1, &num2)
, although the function is written to accept pointers.
Does it make any difference if I pass the address directly instead of passing a pointer? How should I decide in which way I should pass the parameters to such a function?
Upvotes: 0
Views: 113
Reputation: 117681
A pointer is (the type of) an address. I don't know why you use the two words as if they're different things.
When you call f(&x)
first &x
creates a pointer containing the memory address of x
(AKA 'pointing to x
'), and passes that into the function. It's the exact same thing as int* p = &x; f(p)
(assuming the type of x
is int
).
This is no different than g(42)
vs int i = 42; g(i)
, as Eric Postpischil mentions. They are the same thing - temporary vs named variables.
Upvotes: 2