1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M6 Dereferencing
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
00Hrs
57Mins
46Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M6 Dereferencing

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
00Hrs
57Mins
46Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Dereferencing

Overview

Having a treasure map (a Pointer) is useless if you don't actually dig up the gold. Dereferencing is the act of traveling to the memory address stored inside a pointer and physically interacting with the data that lives there.

You dereference a pointer by placing the Dereference Operator (`*`) in front of it. This allows you to not only read the original variable's data, but also overwrite it directly in memory, permanently changing the original variable.

Syntax

cpp
int score = 100;
int* ptr = &score; // ptr holds the address of score

// 1. Reading data via Dereferencing
// We travel to the address and print the data (100)
std::cout << *ptr << "\n"; 

// 2. Mutating data via Dereferencing
// We travel to the address and forcefully overwrite the data with 999
*ptr = 999;

// The original 'score' variable is now permanently 999!
std::cout << score << "\n";

Common Pitfalls

  • Confusing the two uses of the asterisk (*). When declaring a variable (int* p), the asterisk means 'This is a pointer'. When used in front of an existing pointer (*p = 5), it is an action meaning 'Travel to this address and edit the data'.
  • Dereferencing a Null or Wild pointer. If a pointer doesn't hold a valid memory address, putting a * in front of it tells the CPU to jump into protected or non-existent RAM. The OS will instantly terminate your program with an Access Violation or Segfault.

Interview Questions

What happens if you execute int a = 10; int* p = &a; int b = *p; b = 20;? Does a change to 20?

No. a remains 10. int b = *p; simply travels to a, reads the value '10', and creates a brand new, completely separate physical copy of that '10' for b. Changing b later has absolutely zero effect on a.

Real-World Example

Passing a pointer into a function so the function can physically travel back to the main scope and alter a variable.

example
cpp
#include <iostream>

// The function accepts a memory address (a pointer)
void takeDamage(int* healthAddr, int damage) {
    // We dereference the pointer to edit the original health!
    *healthAddr = *healthAddr - damage; 
}

int main() {
    int playerHP = 100;
    
    // We pass the physical address of playerHP
    takeDamage(&playerHP, 25);
    
    std::cout << "HP is now: " << playerHP << "\n"; // Prints 75!
    return 0;
}

Check Your Knowledge

Test your understanding of Dereferencing with these quick questions.

Question 1

In the code `int val = 50; int* p = &val; cout << p;`, what exactly is printed to the screen?

Take C++ Quiz
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Dereferencing

Overview

Having a treasure map (a Pointer) is useless if you don't actually dig up the gold. Dereferencing is the act of traveling to the memory address stored inside a pointer and physically interacting with the data that lives there.

You dereference a pointer by placing the Dereference Operator (`*`) in front of it. This allows you to not only read the original variable's data, but also overwrite it directly in memory, permanently changing the original variable.

Syntax

cpp
int score = 100;
int* ptr = &score; // ptr holds the address of score

// 1. Reading data via Dereferencing
// We travel to the address and print the data (100)
std::cout << *ptr << "\n"; 

// 2. Mutating data via Dereferencing
// We travel to the address and forcefully overwrite the data with 999
*ptr = 999;

// The original 'score' variable is now permanently 999!
std::cout << score << "\n";

Common Pitfalls

  • Confusing the two uses of the asterisk (*). When declaring a variable (int* p), the asterisk means 'This is a pointer'. When used in front of an existing pointer (*p = 5), it is an action meaning 'Travel to this address and edit the data'.
  • Dereferencing a Null or Wild pointer. If a pointer doesn't hold a valid memory address, putting a * in front of it tells the CPU to jump into protected or non-existent RAM. The OS will instantly terminate your program with an Access Violation or Segfault.

Interview Questions

What happens if you execute int a = 10; int* p = &a; int b = *p; b = 20;? Does a change to 20?

No. a remains 10. int b = *p; simply travels to a, reads the value '10', and creates a brand new, completely separate physical copy of that '10' for b. Changing b later has absolutely zero effect on a.

Real-World Example

Passing a pointer into a function so the function can physically travel back to the main scope and alter a variable.

example
cpp
#include <iostream>

// The function accepts a memory address (a pointer)
void takeDamage(int* healthAddr, int damage) {
    // We dereference the pointer to edit the original health!
    *healthAddr = *healthAddr - damage; 
}

int main() {
    int playerHP = 100;
    
    // We pass the physical address of playerHP
    takeDamage(&playerHP, 25);
    
    std::cout << "HP is now: " << playerHP << "\n"; // Prints 75!
    return 0;
}

Check Your Knowledge

Test your understanding of Dereferencing with these quick questions.

Question 1

In the code `int val = 50; int* p = &val; cout << p;`, what exactly is printed to the screen?

Take C++ Quiz

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A