Loading lessons...
Pass by Address
Pass by Address
Instead of a reference, you can pass a variable's address to the function and reach the variable through a pointer. The idea is similar - changes reach the caller - but the syntax uses a pointer parameter.
The pointer parameter
A parameter declared as int (a pointer to an int) stores an address. Inside the body, ptr dereferences the pointer: it gives you the variable that the pointer points at.
void changeValue(int* ptr) {
*ptr = 55; // write 55 into the variable at that address
}
int*is a pointer to an int; it stores an address.*ptrdereferences: it becomes the target variable itself.- Assigning
*ptr = 55writes 55 into that variable.
Passing the address with &
At the call site, you use the address-of operator & to pass the variable's address:
int main() {
int age = 18;
changeValue(&age); // pass the address of age
cout << age; // prints 55
return 0;
}
- The parameter is a copy of the address, not a copy of the value.
- Reading and writing through
*ptrmodifies the caller's variable itself.
Pointer vs reference
Both pass-by-reference (int &) and pass-by-address (int) let a function modify the caller's variable. A reference has cleaner syntax (no to dereference every time), while pointers are prominent in C-style code and with arrays.
TL;DR
- A pointer parameter
int*holds an address. *ptrdereferences - it stands for the variable at that address.- Writing
*ptr = value;changes the caller's variable. - The caller passes the address:
changeValue(&age). - The function receives the address, not a full copy.