info@tutsfinder.in



Pointers


In C++, a pointer is a variable that contains the address of another variable rather than store the value directly. Just the same way as a variable of type int is used to contain an integer value, A pointer varibale is one that is used to contain a memory address.

Syntax :

data_type *pointer_name;


Declaring a Pointer


Type *pointer_variable_name = null; //initializing value

Declaring a pointer to an integer would be:

Int *a=null;


Program to determining the addresses of an int and a double

#include <iostream>
using namespace std;

int main()
{
    int age=20;
    const double Pi = 3.1416;

    cout << "Integer value address  : " << &age << endl;
    cout << "Double value address : " << Π
}


Output :

Integer value address  : 0x7ffda263f844
Double value address : 0x7ffda263f848


Using poiters to stor addresses

Assume a variabe declaration of the types you already know :

//declaraing a variable
Type variable_name = initial_value;

To store the address of a variable in a pointer, you would declare a pointer to the same type and initialized the pointer to the variable’s address using the refrence operator (&):

//declaring a pointer to the same type and iniatializing to address:
Type* pointer = &variable;

Program to demnostrate the declaration and initialization of a pointer

#include <iostream>
using namespace std;

int main()
{
    int age=20;
    int* a = &age;
    
    cout << "Integer value address  : " << a << endl;
}


Output :

'
Integer value address  : 0x7fffe3ce4414


Program that demostrate pointer reassignment to another variable

#include <iostream>
using namespace std;

int main()
{
    int age=20;
    int* a = &age;
    
    cout << "First Age is : " << endl;
    cout << "a is  : " << a << endl;
    
    int myAge =23;
    a = &myAge;
    cout << "My age : " << endl;
    cout << "a is : " << a;
}


Output:

First Age is : 
a is  : 0x7fff188e05c0
My age : 
a is : 0x7fff188e05c4


What is the sizeOf() of a Pointer ?


It returns the no. of bytes required to store, The sizeOf() is a pointer is hence dependent on the compiler and the operating system the program has been compiled for.


Program to demonstrate that pointers to different types have the same sizes –

#include <iostream>
using namespace std;

int main()
{
    int age = 20;
    double pi = 3.1416;
    char sayYes = 'y';
    
    int* a = &age;
    double* p = π
    char* s = &sayYes;
    
    cout << "sizeof(int) = " << sizeof(int) << endl;
    cout << "sizeof(double) = " << sizeof(double) << endl;
    cout << "sizeof(char) = " << sizeof(char) << endl;
    
    cout << "sizeof(a) = " << sizeof(a) << endl;
    cout << "sizeof(p) = " << sizeof(p) << endl;
    cout << "sizeof(s) = " << sizeof(s) << endl;
}


Output:

sizeof(int) = 4
sizeof(double) = 8
sizeof(char) = 1
sizeof(a) = 8
sizeof(p) = 8
sizeof(s) = 8