0
0
C++programming~10 mins

Pointer and variable relationship in C++ - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Pointer and variable relationship
Declare variable x
Assign value to x
Declare pointer p
Assign address of x to p
Access value via *p
Modify x via *p
End
This flow shows how a pointer stores the address of a variable and can be used to access or modify that variable.
Execution Sample
C++
int x = 10;
int* p = &x;
*p = 20;
std::cout << x;
This code creates an integer variable x, a pointer p to x, changes x through p, and prints x.
Execution Table
StepActionVariable xPointer pDereferenced *pOutput
1Declare x and assign 1010undefinedundefined
2Declare pointer p and assign address of x10address_of_x10
3Assign 20 to *p (changes x)20address_of_x20
4Print x20address_of_x2020
💡 Program ends after printing the updated value of x.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
xundefined10102020
pundefinedundefinedaddress_of_xaddress_of_xaddress_of_x
Key Moments - 3 Insights
Why does changing *p also change x?
Because p stores the address of x, *p accesses the value at that address, so modifying *p changes x directly (see Step 3 in execution_table).
What does *p mean in this code?
*p means 'the value at the address stored in p'. Since p points to x, *p is the same as x (see Step 2 and 3).
Why do we use &x when assigning to p?
&x means 'the address of x'. We assign this address to p so p points to x (see Step 2).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of x after Step 3?
A10
B20
Cundefined
Daddress_of_x
💡 Hint
Check the 'Variable x' column at Step 3 in the execution_table.
At which step does pointer p get assigned the address of x?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Action' column in execution_table for when p is assigned.
If we change *p = 30; at Step 3, what will be printed at Step 4?
A30
B10
C20
Daddress_of_x
💡 Hint
Changing *p changes x, so check the 'Variable x' value after Step 3.
Concept Snapshot
Pointer and variable relationship in C++:
- Declare variable: int x = value;
- Declare pointer: int* p = &x; (store address of x)
- Access value via pointer: *p
- Changing *p changes x directly
- &x gives address of x
Pointers hold addresses, *p accesses the value at that address.
Full Transcript
This example shows how a pointer relates to a variable in C++. First, we declare an integer variable x and assign it the value 10. Then, we declare a pointer p and assign it the address of x using &x. The pointer p now points to x. When we assign 20 to *p, we change the value of x through the pointer. Finally, printing x shows the updated value 20. The key idea is that pointers store addresses, and dereferencing a pointer (*p) accesses or modifies the value at that address.