Dereference Operator
Part of the Logic & Flow section of Coddy's C++ journey. Lesson 3 of 56.
*) becomes essential.The dereference operator * is used to access the value stored at the memory address that a pointer is pointing to. When you place * before a pointer variable, it "follows" the address and gives you the actual value stored there.Remember that the address-of operator (&) is used to get the memory address of a variable, while the dereference operator (*) is used to access the value at that address.int number = 42;
int* ptr = &number; // ptr stores the address of number
int value = *ptr; // value now contains 42*ptr, you're actually changing the value stored at that memory location:*ptr = 100; // Changes number to 100
// number is now 100, even though we modified it through ptrChallenge
EasyCreate a program that demonstrates the dereference operator by modifying a variable's value through a pointer.
The following input will be provided:
- An integer representing the initial value for a variable
- An integer representing the new value to assign through the pointer
Your program should:
- Declare an integer variable named
temperatureand initialize it with the first input value - Create a pointer named
tempPtrthat points to thetemperaturevariable - Print the original value by dereferencing the pointer
- Use the dereference operator to change the value of
temperatureto the second input value through the pointer - Print the new value by dereferencing the pointer again
Use the following exact output format:
Original value: [original value]
New value: [new value]Try it yourself
#include <iostream>
using namespace std;
int main() {
// Read input values
int initialValue, newValue;
cin >> initialValue;
cin >> newValue;
// TODO: Write your code below
// 1. Declare temperature variable and initialize with initialValue
// 2. Create tempPtr pointer pointing to temperature
// 3. Print original value using pointer dereference
// 4. Change temperature value through pointer using newValue
// 5. Print new value using pointer dereference
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating ItemsPractice on your own: Online C++ compiler