Saturday, April 19, 2025

C++ Change Variable with Pointer

We can change value in original variable using pointers, and pointers are just memory address where we have real value.

First we are creating an original variable and directly printing it:

int Number = 4323;
cout << "Original Value Atm: " << Number << endl;

Then a pointer is created and memory address printed:

int *ptrNumber = &Number;
cout << "Actual Address: " << ptrNumber << endl;

Then new value for original variable is set USING pointer (we use "*" symbol here)

*ptrNumber = 10000;

And now we can dereference a pointer to get value:

cout << "Value After Change: " << *ptrNumber << endl;

Or we can print value directly using original variable name: 

cout << "Value in Container (Variable): " << Number << endl;

Full script: 

#include <iostream>

using namespace std;

int main() {

    int Number = 4323;
    cout << "Original Value Atm: " << Number << endl;

    int *ptrNumber = &Number;
    cout << "Actual Address: " << ptrNumber << endl;

    *ptrNumber = 10000;
    cout << "Value After Change: " << *ptrNumber << endl;
    cout << "Value in Container (Variable): " << Number << endl;

    return 0;

}

Result:

Original Value Atm: 4323
Actual Address: 0x6dfee8
Value After Change: 10000
Value in Container (Variable): 10000

Process returned 0 (0x0)   execution time : 0.062 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 .  ...