0
0
C++programming~10 mins

Why pointers are needed in C++ - Visual Breakdown

Choose your learning style9 modes available
Concept Flow - Why pointers are needed
Declare variable
Get variable address
Store address in pointer
Use pointer to access/change variable
Reflect changes in original variable
This flow shows how pointers hold the address of a variable to access or change its value indirectly.
Execution Sample
C++
int x = 10;
int* p = &x;
*p = 20;
std::cout << x;
This code changes the value of x using a pointer p that stores x's address.
Execution Table
StepActionVariableValueExplanation
1Declare xx10Variable x is created with value 10
2Declare pointer ppaddress of xPointer p stores the address of x
3Change value via pointer*p20Value at address p points to (x) is changed to 20
4Print xx20x now holds 20 after change through pointer
💡 Program ends after printing updated value of x
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
xundefined10102020
pundefinedundefinedaddress of xaddress of xaddress of x
Key Moments - 2 Insights
Why do we need to use *p to change x's value?
Because p stores the address of x, *p means 'value at that address'. Changing *p changes x indirectly, as shown in step 3 of the execution_table.
Why can't we just assign p = 20?
p is a pointer and must hold an address, not a direct value. Assigning 20 to p would be wrong. Step 2 shows p stores x's address, not a number.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what does *p = 20 do?
AChanges the address stored in p
BChanges the value of x to 20
CCreates a new variable with value 20
DDoes nothing
💡 Hint
Refer to step 3 in execution_table where *p changes value to 20
At which step does the value of x change?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Check variable x in variable_tracker after step 3
If we remove * from *p = 20, what happens?
Ap changes to 20
BCompilation error
Cx changes to 20
DNothing changes
💡 Hint
Without *, p is assigned 20 directly, changing the pointer value (see pointer behavior in execution_table step 2)
Concept Snapshot
Pointers store addresses of variables.
Use * to access or change the value at that address.
Pointers let you change variables indirectly.
This is useful for efficient memory use and sharing data.
Syntax: int* p = &x; *p = newValue;
Full Transcript
Pointers are variables that hold the address of another variable. In this example, we declare an integer x with value 10. Then we declare a pointer p that stores the address of x. Using *p means accessing the value at the address p points to. When we assign *p = 20, we change the value of x indirectly through the pointer. This is why pointers are needed: they allow indirect access and modification of variables, which is useful in many programming situations like passing large data efficiently or working with dynamic memory.