Published by
Mar 9, 2012 (last update: Mar 22, 2012)

PointersSimplified

Score: 3.8/5 (20 votes)
*****

Pointers Simplified:

As the name says a pointer is a special type of variable which is used to point at another variable/pointer.

Declaring ,assigning value to a Pointer, retrieving the value:

Declare a pointer:

Pointer variables are declared by prefixing with * symbol.
1
2
3
4
 //<datatype*> pointervariablename;
 int   *gunpointer=0; 
 int* gunpointer=0;
 float* fp;

now lets declare some variables to point at
int ivalue=10;
float fvalue=5.0;

Pointing the gun/pointer:

1
2
3
4
5
 
  gunpointer=ivalue; /*invalid u cant point the gun without knowing where the  person is*/
gunpointer=&ivalue;/*valid now u know the address, u can point at the person residing at that address*/
gunpointer=&fvalue;/*invalid wrong gun choice,ur using a toy gun to rob a bank
 a pointer can only point to a variable of same type*/

Firing the gun or dereferencing the pointer: (fetching the value from a pointer)

Now once the pointer is pointing to a variable, how do you get the value of pointed location or dereference a pointer?
Simple by using the * mark again
1
2
int ivalue1=*gunpointer;//fetches the value stored at that location
printf("%d",ivalue1);

Note: * is used in two places

1
2
 int* ip ;//  here it means u are declaring a pointer to an integer.
 int k=*ip;//or printf(ā€œ%dā€,*ip);  here it means dereferencing or fetching the  

value stored at the address pointed by pointer.

Taking a deeper plunge:(caution things can go really bersek from here )


Two dimensional Pointers:

they can be considered as pointers to pointers

ex1:pointer to a pointer


1
2
3
    char* str="hi im learning pointers";
    char** strp=&str;
    printf("%s",*strp);

here strp acts as a pointer to str which is pointing to the starting address of string "hi im learning pointers"

This concept is very useful when an array has to be populated using pass by reference

ex2 (complicated ):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<iostream>
#include<conio.h>
void populatearray(int** mainarray,int* count)
{
    int a[]={1,2,3,4,5};
    //create a single dimension array for storing the values
    int* myarray=new int[5];
    //assign the values to be stored to the array
    for(int i=0;i<5;i++)
    {
        myarray[i]=a[i];
    }
    //store the count in the adress pointed by formal parameter
    *count=5;
    //store the array in the adress pointed by formal parameter
    *mainarray=myarray;
}
void main()
{   //the main array where values have to be stored
    int* arraymain=0;
    //count of elements
    int maincount=0;
    //pass the adess of pointer to array, adress of counter
    populatearray(&arraymain,&maincount);
    //check whether pass by reference has worked
    printf("The array Elements:\n");
    for(int i=0;i<maincount;i++)
    {
        printf("\n%d",arraymain[i]);
    }
    getch();
}