简体   繁体   中英

Why pass by pointer when we can pass the variable's address with the & operator?

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?

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) 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) int i = 42; g(i) , as Eric Postpischil mentions. They are the same thing - temporary vs named variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM