Sunday, February 24, 2013

Pointer Operations Demo

#include<stdio.h>
#include<conio.h>
void main(){
int arr[5]={12,13,14,15,16};
int *ptrArr, *ptrArr1,i;
clrscr();

ptrArr = arr;
printf("\nPrinting the first element of array: %d\n\n",*ptrArr);

Pointer variable can be increased. If added 1 to it, it will point to the
next element of the same array

for(i=0;i<5;i++){
printf("%d\t", *ptrArr);
ptrArr++;
}
printf("\n\n");

Now the Pointer is pointing to a memory location that is not reserved
so if you will print the value at pointer location it will print garbage
and some times it show any RUN TIME error because C compiler will not
check array boundaries

printf("Printing value at pointer location that is not reserved by the program\n");
printf("%d This is garbage\n\n",*ptrArr);

Pointer varible can be decreased and if we are decreasing 1 to it,
it will start pointing to the previous element in the same array

for(i=0;i<5;i++){
ptrArr--;
printf("%d\t", *ptrArr);
}
printf("\n\n");

Now, ptrArr will point to 3rd element of array

ptrArr = &arr[2];

printf("\nThird element of an array : %d",*ptrArr);

One pointer can be subtracted from another if they are poining to
elements of same array and the operation will return no of elements
in between these two pointer locations

ptrArr1 = &arr[5];

printf("\n\nSubtraction of two pointers ptrArr1 - ptrArr : %d\n",ptrArr1 - ptrArr);

getch();
}

Note:
Two Pointers cannot be added
A pointer cannot be multipled with a number
A pointer cannot be divided by a number

Output:

Printing the first element of array: 12

12 13 14 15 16

Printing value at pointer location that is not reserved by the program
0 This is garbage

16 15 14 13 12


Third element of an array : 14

Subtraction of two pointers ptrArr1 - ptrArr : 2

No comments:

Post a Comment