简体   繁体   中英

Using pointers to emulate Pass-by-Reference in a Pass-by-Value function (C and C++)

So I am trying to understand a simple piece of code that 'emulates' Pass-by-reference using pointers in a Pass by value function. The example is given as a C practice since there is no Pass by reference in C. but I am also curious about its effects on C++.

so after running this code the values are swapped:

void swap(int* a, int* b)
{
  int temp;
  temp = *a;
  *a = *b;
  *b = temp;
}

I am trying to understand why passing pointers as arguments create a pass-by-reference effect? Does it mean all actions that are performed through pointers have a pass-by-reference effect? So the swapped memory location will not go back once we quit the function? Would this also be valid in C++?

New to coding so I hope I could make myself clear.

Basically, your code is copying a memory address to the function, while if you omitted the * operator, the function would be copying what's a memory address to the function. 内存地址的功能。 Here's what each line is essentially saying.

// Give me the memory address of a and b.
void swap(int* a, int* b)
{
  int temp;
  // Whatever value is at memory address 'a', copy it to temp.
  temp = *a; 
  // Whatever value is at memory address 'b', copy it to memory address 'a'.
  *a = *b;
  // Copy temp over the value at memory address 'b'.
  *b = temp;
}

And yes, it would be equally valid in C++.

You can basically think of pointers and references as the same thing. They both refer to addresses. So if you pass an address (either as pointer or as reference) to a function, and the content of the address changes, then the change is still there at the end of the function.

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