0
0
CppHow-ToBeginner · 3 min read

How to Pass by Pointer in C++: Syntax and Examples

In C++, you pass by pointer by declaring a function parameter as a pointer type using *. You then pass the address of a variable using the & operator, allowing the function to modify the original variable.
📐

Syntax

To pass by pointer, declare the function parameter with an asterisk * to indicate it is a pointer. Inside the function, use the dereference operator * to access or modify the value pointed to. When calling the function, pass the address of the variable using the address-of operator &.

  • Parameter: type *name means a pointer to type.
  • Argument: &variable passes the address of variable.
  • Dereference: *pointer accesses the value at the pointer.
cpp
void updateValue(int *ptr) {
    *ptr = 10; // Change value at the pointer
}

int main() {
    int num = 5;
    updateValue(&num); // Pass address of num
    return 0;
}
💻

Example

This example shows how to pass an integer by pointer to a function and modify its value. The function changeNumber receives a pointer to an integer and sets the value to 20. The original variable number is changed after the function call.

cpp
#include <iostream>

void changeNumber(int *ptr) {
    *ptr = 20; // Modify the value pointed to
}

int main() {
    int number = 5;
    std::cout << "Before: " << number << std::endl;
    changeNumber(&number); // Pass address of number
    std::cout << "After: " << number << std::endl;
    return 0;
}
Output
Before: 5 After: 20
⚠️

Common Pitfalls

Common mistakes when passing by pointer include:

  • Passing the variable directly instead of its address, causing a type mismatch.
  • Dereferencing a null or uninitialized pointer, which leads to crashes.
  • Forgetting to use the * operator inside the function to access the value.

Always ensure the pointer is valid and points to a proper variable before dereferencing.

cpp
/* Wrong: passing variable instead of address */
void wrongFunction(int *ptr) {
    *ptr = 10;
}

int main() {
    int x = 5;
    // wrongFunction(x); // Error: cannot convert int to int*
    wrongFunction(&x); // Correct
    return 0;
}
📊

Quick Reference

Tips for passing by pointer in C++:

  • Use type *param to declare a pointer parameter.
  • Pass the address of the variable with &variable.
  • Use *param inside the function to access or modify the value.
  • Check pointers for null if necessary before dereferencing.

Key Takeaways

Pass by pointer requires declaring function parameters as pointers using *.
Pass the address of a variable using & to allow the function to modify the original value.
Use the dereference operator * inside the function to access or change the pointed value.
Avoid passing variables directly instead of their addresses to prevent type errors.
Always ensure pointers are valid before dereferencing to avoid runtime errors.