Saturday, April 19, 2025

C++ Pointers as Arguments

Pointers can be used as parameters.

In this case function will demand a pointer to a variable whose data type must be an integer.

We will add integer 1000 to value that is at that specific memory address.

Once we create function outside main() section it's easy:

void add_1000(int *xPtr) {
    cout << "Result of add: " << (*xPtr) + 1000 << endl;
}

Inside main() section variable will be created, with value 5 in this example:

int Number = 5;

Then a pointer is created with a dedicated line:

int *ptrNumber = &Number;

And than a call of our function where we provide memory location as argument:

add_1000(ptrNumber);

Full source: 

#include <iostream>

using namespace std;

void add_1000(int *xPtr) {
    cout << "Result of add: " << (*xPtr) + 1000 << endl;
}

int main() {

    int Number = 5;
    int *ptrNumber = &Number;

    add_1000(ptrNumber);

    return 0;

}

Result:

Result of add: 1005

Process returned 0 (0x0)   execution time : 0.072 s
Press any key to continue.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...