How will we read complex pointer ?
Rule 1. Give the first priority to the name (identifier) of pointer variable.
Rule 2. Give the least priority of to the data type with modifier (like int,char,float,unsigned int,static int etc.)
Rule 3. () and [] operator has higher priority (associativity left to right ) than * ,& (associativity right to left)
Priority: It means operator which have highest priority will execute first.
Associativity: If associativity is left to right and two operator have same priority then left most operator will have more priority and vice versa.
(to read the priority and associativity of each operator click here)
How to read
If right side of name (identifier) is ( ) then read function after the function read all as return type
Read [ ] operator array and after this read as it contain
Read * pointer if you have not encounter function or array otherwise read address.
If you will read example then you will understand more easily.
Example 1.
Read the pointer
int (*ptr)();
Ans:
Give first priority to ptr :1
There are two () operator ,associativity of () operator is left to right so left most operator will have more priority.
Left most ( ) operator will execute first . So give * to the second priority and right most ( ) operator to the third priority.
Give fourth priority to int
Read : ptr is pointer to such function which return type is integer data type.
Program:
#include
#include
void main()
{
int (*ptr1)();
int (*ptr2)();
void (*ptr3)();
ptr1=puts;
ptr2=getch;
ptr3=clrscr;
(*ptr3)();
(*ptr1)("POWER OF POINTER");
(*ptr2)();
Output: POWER OF POINTER
Example 2.
char *arr [3];
Ans :
arr is array of size 3 which contain address of char
program:
void main()
{
char *arr[3];
char a=1,b=2,c=3;
arr[0]=&a;
arr[1]=&b;
arr[2]=&c;
clrscr();
printf("%u %u",&b,arr[1]);
printf("\n%d",*arr[2]);
getch();
}
Output :
any addresss same address
3
Example 3
char (*ptr)[5];
Ans:
ptr is pointer to array of size 5 which contain char data type.
Program:
#include
#include
void main()
{
char arr[5]={1,2,3,4,5};
char (*ptr)[5];
ptr=&arr;
ptr=(*ptr)+2;
clrscr();
printf("%d",**ptr);
getch();
}
Output: 3
Example 4
unsigned long int ( * avg ())[ 3]
Program:
Ans:
avg is such function which return type is address of array of size of 3 which contain unsigned long int data type.
Program:
#include
#include
unsigned long int (* avg())[3]
{
static unsigned long int arr[3]={1,2,3};
return &arr;
}
void main()
{
unsigned long int (*ptr)[3];
ptr=avg();
clrscr();
printf("%d",*(*ptr+2));
getch();
}
Output :3
0 comment here::
Post a Comment