Table of Contents
Passing by pointer allows a function to receive the address of an object through a pointer parameter. The function can then use the pointer to access or modify the original object.
Unlike a reference parameter, a pointer parameter can also represent a null pointer, allowing the function to determine whether a valid object was supplied.
Source Code #
#include <iostream>
void updateValue(int* value)
{
*value = 100;
}
int main()
{
int number = 50;
updateValue(&number);
std::cout << "Number: " << number << '\n';
return 0;
}
Output #
Number: 100
Explanation #
int* valuedeclaresvalueas a pointer parameter that can store the address of anintobject.&numberobtains the memory address of the variablenumber.updateValue(&number)passes that address to the function.valuetherefore points to the originalnumberobject.- The dereference operator (
*) accesses the object stored at the address held byvalue. *value = 100;modifies the originalnumbervariable through the pointer.- After the function returns,
numbercontains100. - Unlike a reference, a pointer can be assigned
nullptrto represent the absence of an object. - A pointer should be dereferenced only when it points to a valid object.