Test your Programming knowledge

50% users failed to get the best score. It's your turn to test now.
Questions curated by the expert mentors at codzify.com

Start Quiz

Article

Pointers in C++ Programming

3 min 30 sec read

What happens in memory when we write statement like this ?

int i = 3 ;

Compiler will tell the memory to store value 3 at some location and name that location as 'i' .It looks like this ,

 

Diagram itself is explanatory. The value of 'i' is 3 and it is stored at some location Number . You don't have to worry about the location Number . Memory will automatically handle this.

 

#include 
using namespace std;
int main()
{
  int a = 5;
  cout <<"Address of variable a = "<< &a <<"
";

  cout<<"Value of variable a = "<< a << "
";


  cout<<"Value of variable a = "<< *(&a);
  return 0;
}

Output

Address of variable a = 12345678
Value of variable a = 5
Value of variable a = 5

* asterik indicates that the variable is pointer variable. The third cout statement

 cout<<"Value of variable a = "<< *(&a);

Here , first we get the address of variable 'a' using &a and apply that address * to get the value at that specific address.

What are Pointers ?

Pointers are used to get the value at specific address Simple and Easy Defination. Pointers are denoted by *(Asterik symbol).

Syntax

datatype *variableName;

Example

int *a;
float *b;
float **b;
float ***b;

Pointers Concept Example

int i=3;                                              
j = &i;  

Always read * as "Value at"

 Assume 1000 & 1004 are the addresses of i & j
   i 
 1000 --> 3  
                                                                     
   j
1004 --> 1000    
                            
            
*j -->  Read Value at j 
        Value at 1000
        What is the value at 1000 Address ? :) 

*j --> 3                    
   

/* Yes you have to read the pointers like this. */

Example :-

#include 
using namespace std;
int main()
{
    int i=3, *j, k;
    j = &i;
    cout<< i * *j * i + *j;
    return 0;
}

Output :-

30

Compute the value of j like i explained in above example.

i = 3

*j = 3

i * *j * i + *j 
3 * 3 * 3 + 3  = 30

Always remember , Practice makes you perfect in Pointers :)

Recommended Articles

  1. Functions in C++
  2. Switch Statements in C++
  3. Array in C++

Did you found this article helpful?

Try to execute what you have learnt

Easy to use online data structure compiler where you can execute the programs in your favourite programming language.
(C, C++, Python)

Open Compiler

HTML, CSS and Javascript Real time Web Editor

Execute your HTML, CSS and javascript code in real time with the web editor
(HTML, CSS, Bootstrap, Javascript)

Open Web Editor