• Home
  • 6.11 Passing by Pointer

6.11 Passing by Pointer

View Categories

6.11 Passing by Pointer

< 1 min read

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* value declares value as a pointer parameter that can store the address of an int object.
  • &number obtains the memory address of the variable number.
  • updateValue(&number) passes that address to the function.
  • value therefore points to the original number object.
  • The dereference operator (*) accesses the object stored at the address held by value.
  • *value = 100; modifies the original number variable through the pointer.
  • After the function returns, number contains 100.
  • Unlike a reference, a pointer can be assigned nullptr to represent the absence of an object.
  • A pointer should be dereferenced only when it points to a valid object.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *