Sunday, August 26, 2018

Pointers


A data structure that can be modified during program's execution by expanding or contracting without specifying a fixed size is known as dynamic data structure. These are used in almost all type of applications and programs. Such dynamic memory allocation achieved during execution by using special memory address storing variables called pointers.

What is pointer?

Each memory cell in the digital computer has an address that can be used to access that location’s stored value. Program can access and change the contents of this memory location via the pointer. Therefore, a pointer variable points to a memory location.

Usage of Pointer

datatype  *ptr_variable_name ;

The '*' asterisk is symbol of pointer variable and must be included before name while declaring.

To point to character type data, declare char type pointer and then assign address to it.

char name[30];

char *ptrName;

ptrName = &name[0];

ptrName++;                   

//it jumps one byte as it is char data type pointer

To point to integer type data, declare int type pointer and then assign address to it.

 

int num[10];

int *ptrNum;

ptrNum = &num[0];

ptrNum++;                   

//it jumps two bytes as it is int data type pointer

Similarly, for float data type float pointer is declared which jumps 4 bytes and so on. Note that this byte size per each data type data varies from machine to machine, for example for Mobile Processor it is very small, for desktop PC it is medium and for mainframe computers it is very large.

For address jump details see the above static and dynamic variable example section.

It is easy to traverse through entire big array using simple pointer variable. You can pass address of array to function instead of passing entire array or copy of array. Thus reducing memory load on program is achieved.

Pointer variable = value by reference.

Suppose an integer array holds 100 integer data, then declare an integer type pointer and assign it address of first element of this array.

int array[100];         //declare an integer array

int *ptrArray;         //declare an integer pointer

ptrArray=&array[0];//assign array address to pointer

......

printArray(ptrArray);

//pass array address to function

....

num = ptrArray + 5;   //access array[5] value

ptrArray++;           //increment array index

Indirection Operator

As name implies pointer variable only points to a variable that means stores only address of a variable that actually holds data.

int num;       //address of num = 21260 [say]

int *ptrNum;  //declare int type pointer

 

num = 45;     //21260 = 45

 

//how to assign address of variable to pointer?

ptrNum = # //ptrNum = 21260

 

//what happens if address of variable is assigned to pointer?

ptrNum = 21260;   

//compiler error, you can only assign address of variable to pointer.

 

//how to print variable value?

printf ( “num = %d “, num);                //num = 45

 

//how to print variable address?

printf ( “address of num = %u “,&num);    

//address of num = 21260 [using & address operator]

[Since pointer variable is not an integer, but displayed as unsigned integer %u is used]

 

//how to print pointer variable’s address & its [reference address] value?

printf ( “ptrNum address = %u”, ptrNum);  

// ptrNum address = 56789 [say]  

printf ( “ptrNum value = %d”, ptrNum);              

// ptrNum value = 21260     

 

//how to print value of variable which pointer is pointing?

printf ( “ptrNum value content = %d”, *ptrNum);

// ptrNum value content = 45 [num=45]

 

//how to change value of variable using pointer?

*ptrNum = 38;           

//num=38 [by using dereference/indirection operator ‘*’ before pointer variable]

 

Pointer Expressions and Pointer Arithmetic

The conversion specifier for a pointer is add and subtracted with exception that they jump according to data type they are referencing. For example, character type pointer jumps one byte if it is incremented by one and integer type jumps for two bytes.

It is highly recommended to use parenthesis around pointers to set right order of evaluation in expression and give clear image of the expression to the reader. For example, *ptr1/*ptr2 will yield compiler error as ‘/*’ is block comment symbol.

//Since pointers stores memory address, they can be used for comparison operations.

ptr1 > ptr2

ptr1 != ptr2

 

//pointer’s dereferencing value can be used to perform arithmetic operations.

*ptr1 = (*ptr1) + (*ptr2);

Sum = (*ptr1) + 10;

Sum+= (*ptr1);

 

//but pointer variables are not integers you cannot perform arithmetic operations directly on them.

ptr1 + ptr2 //is illegal

ptr1 - ptr2 //is illegal

ptr1 / ptr2 //is illegal

 

Pointers And Functions

The pointers make complex functions looks simple and easily accessible. The usage of the pointers in a function definition may be classified into two groups:

1.    Call by value

2.    Call by reference

Call by value functions

The copy of parameter values are passed to functions and are treated as local variables inside function. Such method is called call by value data transfer method. Such functions do not change actual value of parameters.

main()

{

int a = 10 , b = 20 ;

printf (“ a = %d  b = %d”, a , b );   //a=10 b=20

function ( a , b ) ;    //direct values are passed

printf (“ a = %d  b = %d”, a , b );   //a=10 b=20

}

 

function ( int x , int y) //call by value: x=10 y=20

{

x = x + 10 ; y = y + 20;

//values transferred to local variables

printf (“ x = %d  y = %d”, x , y );   //x=20 y=40

}

Call by reference functions

Here the address of parameter values are passed to functions and are referred to actual variables inside function. Such method is call call by reference data transfer method. Such functions change actual value of parameters.

main()

{

int a = 10 , b = 20 ;

printf (“ a = %d  b = %d”, a , b );   //a=10 b=20

function ( &a , &b ) ;  //direct values are passed

printf (“ a = %d  b = %d”, a , b );   //a=20 b=40

}

 

function ( int x , int y) //call by value: x=10 y=20

{

x = x + 10 ; y = y + 20;             

//reference transferred to local variables

printf (“ x = %d  y = %d”, x , y );   //x=20 y=40

}

Pointer and Arrays

For one dimensional array, declare pointer and assign address of first element of array. Then increment or decrement pointer to traverse through entire array.

//how to assign array to pointer?

int a[‘ ’] , *ptrArray ;             

//declare unspecified size int type array and int type pointer

ptrArray = &a[0]; or ptrArray = a ;

// ptrArray = address of a[0]

 

//how to access 1st index address of array using pointer?

ptrArray++ ;                      //ptrArray = address of a[1]

 

//how to access 6th index address & its contents of array using pointer?

ptrArray+6 ;                   //ptrArray = address of a[6]

num =*(ptrArray+6 ) ;          //num = value of a[6]

 

For multi-dimensional array, the procedure is same as above. The array elements are stored sequentially in memory, even for multi-dimensional one. So, see below example for accessing elements of such arrays using pointer. 

 


int marks[2][2][3];  

//to store 2*2*3=12 elements as {0,1 ,2,3,4,5,6,7,8,9,10,11}

//memory map will be as below:

         

marks[0][0][0]= 0;

//fills right most dimension first then moves towards left

marks[0][0][1]= 1;

marks[0][0][2]= 2;

marks[0][1][0]= 3; 

//second from right most dimension fills it’s all combinations

marks[0][1][1]= 4;

marks[0][1][2]= 5;

marks[1][0][0]= 6; 

//third from right most dimension fills it’s all combinations

marks[1][0][1]= 7;

marks[1][0][2]= 8;

marks[1][1][0]= 9;

marks[1][1][1]= 10;

marks[1][1][2]= 11;

//how to assign multi-dimensional array to pointer?

int *ptrMarks ;                   //declare int type pointer  

ptrMarks = &marks[0][0][0]; or ptrMarks = marks;    

// ptrMarks = address of marks[0][0][0]

 

//how to access 1st index address of array using pointer?

ptrMarks ++ ;          // ptrMarks = address of marks[0][0][1]

 

//how to access 6th index address & its contents of array using pointer?

ptrMarks +6 ;             // ptrMarks = address of a[1][0][0]

num =*( ptrMarks +6 ) ;   //num = value of a[1][0][0] = 6

 

Pointer and Strings

In C language there is no data type called string, it is made of char data type array terminated by null character. So access any string, declare pointer and assign address of first element of character array. Now increment or decrement pointer to traverse through entire string.

//how to assign string to pointer?

char name[‘ ’] = “India is great!” , *ptrName ;

//declare char type array [& initialize], char type pointer

ptrName = &name[0]; or ptrName = name ;   

// ptrName = address of name[0] / letter ‘I’

 

//how to access 1st index address of string using pointer?

ptrName ++ ;       // ptrName = address of name[1]/letter ‘n’

 

//how to access 6th index address & its contents of string using pointer?

ptrName +6 ;       // ptrName = address of name[6]/letter ‘i’

num =*( ptrName +6 ) ;       // num = value of name[6] = i

 

//how to traverse through entire string using pointer?

while ( *ptrName != ‘\0’ )      

// loop till string terminator or null terminator is not found.

{

printf(“%c”,name);

name++;

}    

Array of Pointers

As integer type array holds int type elements, pointer array holds address of variables. So access any address, declare pointer array and assign address of variables to each element of it.

//how to declare and assign variables to pointer array?

int a =10 , b =20, c =30;

int *ptrArray[3] ;    //declare int type pointer array

ptrArray[0] = &a;    // ptrArray[0]  = address of variable a

ptrArray[1] = &b;    // ptrArray[1]  = address of variable b

ptrArray[2] = &c;    // ptrArray[2]  = address of variable c

 

//how to access index value and its reference value in pointer array?

for ( int i = 0; i <=4 ; i++ )

     printf ( “ ptrArray[%d] = %u & its value is %d \n”,

i , ptrArray[i] , *(ptrArray[i]) );

 

Possible Output:

ptrArray[0] = 65516 & its value is 10

ptrArray[1] = 65518 & its value is 20

ptrArray[2] = 65520 & its value is 30

 

//can we assign another array address to pointer array?

int a[ ] = { 1 , 2 , 3 , 4 , 5 ) ;

int *ptrA[5] { a , a+1 , a+2 , a+3 , a+4} ; 

 

Pointers to Pointers

We can inherit address of one variable to pointer variable and that to another pointer variable and so on. So this hierarchy can be created by adding extra pointer symbol or asterisk ‘*’ to pointer variable.

//how to declare and assign pointer variable to pointer-pointer variable?

int a =10 ;

int *ptrA ;               //declare int type pointer variable

int *ptrPtrA ;     //declare int type pointer-pointer variable

 

ptrA = &a;        // ptrArray  = address of variable a

ptrPtrA = &ptrA ;// ptrPtrA = address of pointer variable ptrA

 

//how to accesses pointer variable to pointer-pointer variable values?

printf ( “ address of a = %u & its value is %d \n”,

 ptrA , *ptrA );

printf ( “ address of a = %u & its value is %d \n”, 

*ptrPtrA , **ptrPtrA );

 

possible output:

address of a = 65516 & its value is 10

address of a = 65516 & its value is 10

 

 

Memory Address

Contents

int a = 10;

65516

10

 

 

 

ptrA = &a;

782212

65516

 

 

 

ptrPtrA = &ptrA;

12332456

782212

 


Previous Page Main Contents Next Page

No comments:

Post a Comment