Arithmetic - Assignment
Lesson 3 of 14 in Coddy's C++ Pointers course.
Pointers, like other variables and data types, can have arithmetical/mathematical operations performed on them.
Assigning Values
At a given moment a pointer can point to only one address. But, throughout the program that can be changed and the pointer can be modified to point to something else.
Note: Multiple pointers can point to the same location.
int var = 5;
int *ptr = &var;
int *newPtr = ptr;
cout << "Pointer address: " << ptr << endl;
cout << "2nd pointer address: " << newPtr;Output:
Pointer address: 0x7fffca8285cc
2nd pointer address: 0x7fffca8285ccThe value of the pointer ptr got assigned to newPtr and now both pointers are pointing to the same variable var, or to the memory address that holds the value 5
int x = 10;
int *ptr = &x;
int *newPtr = ptr;
cout << "x = " << x << endl;
cout << "ptr = " << ptr << endl;
cout << "*ptr = " << *ptr << endl;
*newPtr = 25;
cout << "x = " << x << endl;
cout << "newPtr = " << newPtr << endl;
cout << "*newPtr = "<< *newPtr;Output:
x = 10
ptr = 0x7ffe28364c9c
*ptr = 10
x = 25
newPtr = 0x7ffe28364c9c
*newPtr = 25As you can see, we have the integer variable x which equals to 10 we declare the pointers ptr and newPtr to point to the same variable x, we can notice if we look at the memory addresses. Now, we changed the value of *newPtr to 25 and that automatically switched the value of x since newPtr is pointing to it.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyOn standard input, you will be given 2 numbers. Input them in variables of your choice, the important part is to create an integer pointer called *ptr and initialize it to point to the first number. Then, assign the value of the second number to the pointer by dereferencing it, and print out its value to standard output
Try it yourself
#include <iostream>
using namespace std;
int main()
{
// Enter your code
return 0;
}All lessons in C++ Pointers
1Pointer Fundamentals
Introduction to PointersDeclaration & InitializationArithmetic - AssignmentArithmetic - OperationsConst PointersPointers & Arrays2Pointers & References
Pointers as ParametersReferences - &References as ParametersPointers vs References