Pointer Operations Demo in C
Here, we will demonstrate pointer operations in C programming.
#include#include 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
Couldn’t Understand. Why not explain everything
Sorry. I dint get your question.
excellent…..
It seems to be a decent code block, but, even with experience of dynamic allocation using malloc, and double pointers.. I feel like you under explained this code.
no that clear
whatever company asked pointer related questions? i want that kind of programs can you post me…
I don’t see utility using two pointers like **p for e.g.
Could you explain this part? please.
can u explain more precise of the relation between array and pointer with various examples
awesome..
sir can we use
ptrArr = arr[2];
instead of ptrArr = &arr[2];