C++ DSA Pointers
C++ DSA Pointers
Home My courses CONT_23CSH-103 :: ELEMENTARY DATA STRUCTURES USING C++ Chapter 2.3
CO3 - Analyze and explain the behavior of linear data structure operations using the
programming addressed in the course.
C++ Pointers
In C++, pointers are variables that store the memory addresses of other variables.
Address in C++
If we have a variable var in our program, &var will give us its address in the memory. For example,
int main()
{
// declare variables
int var1 = 3;
int var2 = 24;
int var3 = 17;
Output
Address of var1: 0x7fff5fbff8ac
Address of var2: 0x7fff5fbff8a8
Address of var3: 0x7fff5fbff8a4
Notice that the first address differs from the second by 4 bytes and the second address differs from the third by 4
bytes.
Note: You may not get the same results when you run the program.
C++ Pointers
As mentioned above, pointers are used to store addresses rather than values.
int *pointVar;
int* pointVar, p;
Note: The * operator is used after the data type to declare pointers.
Here, 5 is assigned to the variable var. And, the address of var is assigned to the pointVar pointer with the code pointVar
= &var.
In the above code, the address of var is assigned to pointVar. We have used the *pointVar to get the value stored in
that address.
When * is used with pointers, it's called the dereference operator. It operates on a pointer and gives the value pointed
by the address stored in the pointer. That is, *pointVar = var.
Note: In C++, pointVar and *pointVar is completely different. We cannot do something like *pointVar = &var;
return 0;
}
Output
var = 5
Address of var (&var) = 0x61ff08
pointVar = 0x61ff08
Content of the address pointed to by pointVar (*pointVar) = 5
For example,
int var = 5;
int* pointVar;
Here, pointVar and &var have the same address, the value of var will also be changed when *pointVar is changed.
// print var
cout << "var = " << var << endl;
// print *pointVar
cout << "*pointVar = " << *pointVar << endl
<< endl;
// print var
cout << "var = " << var << endl;
// print *pointVar
cout << "*pointVar = " << *pointVar << endl
<< endl;
// print var
cout << "var = " << var << endl;
// print *pointVar
cout << "*pointVar = " << *pointVar << endl;
return 0;
}
Output
var = 5
*pointVar = 5
Previous activity
◄ PPT Lecture 2.2.3
Jump to...
Next activity
PPT Lecture 2.3.1 ►
POWERED BY CHANDIGARH UNIVERSITY