How to pass an address to a pointer in c++ function

When we are passing a value to a function we are actually passing a copy of that value to the function where the function can later use that value for it’s own needs. If we want the original value to be changed by that function then we should not pass the copy of that value to that function but instead should pass in the memory address of that value to the function so the function will be able to manipulate the value under that address directly.

Every time we run the program the value will have different memory address assigns to it by the computer but that is not what we really need to care about, all we need to know is the address of that value at the run time of the program. To access an address of a value all we need is to create a pointer which will point to that address then we will be able to manipulate the value in that address memory directly in our program.

Here is how we declare a pointer…

int *p

As you can see we will need to declare the type of data that pointer is pointed to, in this example, it is an integer.

Next we can assign the address of a variable to the pointer like this…

int a = 10;
p = &a; //the & in front of that variable gets the address of that variable and then assigns it to the pointer  

Now you can simply change the value of the original variable with below statement…please take note that we need to put the indirection operator (*) in front of the pointer every time we use it in our program.

*p = 20;

Here is the method to pass the address of a value to the pointer in the function…

multiply_by_ten(&number);

Then we will write the function declaration in this manner…

void multiply_by_ten(int *p);

The below program will change the value of the original number by multiplying that number by ten…

#include <iostream>

using namespace std;
void multiply_by_ten(int *p);

int main()
{
    int number = 20;
    cout << "before multiply : " << number << endl;
    multiply_by_ten(&number);
    cout << "after multiply by ten : " << number << endl;
    
    return 0;
}

void multiply_by_ten(int *p) {
    *p = *p * 10;
}

Besides manipulate a single value we can also make the pointer pointing to an address of a slot in the array and then change the value of that slot accordingly. Below is another program which will multiply the second element in the array with 10.

#include <iostream>

using namespace std;
void multiply_by_ten(int *p);

int main()
{
    int number[] = {1, 7, 3, 4, 5};
    int value = 0;
    cout << "before multiply : " << number[1] << endl;
    multiply_by_ten(&number[1]);
    cout << "after multiply by ten : " << number[1] << endl;
    
    return 0;
}

void multiply_by_ten(int *p) {
    *p = *p * 10;
}

Many people are confuse with pointer but once they have used it everyday in their program then they will really like what pointer can help them to achieve.

Like this post? Kindly share!