Multilevel pointers in c programming

Multilevel pointers: A pointer is pointer to another pointer which can be pointer to others pointers and so on is know as multilevel pointers. We can have any level of pointers.


Examples of multilevel pointers in c:

(1) What will be output if you will execute following code?


#include<stdio.h>
int main(){
int s=2,*r=&s,**q=&r,***p=&q;
printf("%d",p[0][0][0]);


return 0;
}

Output: 2
Explanation:

As we know p[i] =*(p+i)
So,
P[0][0][0]=*(p[0][0]+0)=**p[0]=***p
Another rule is: *&i=i
So,
***p=*** (&q) =**q=** (&r) =*r=*(&s) =s=2


(2) What will be output if you will execute following code?


#include<stdio.h>
#define int int*
int main(){

    int *p,q;
p=(int *)5;
q=10;
printf("%d",q+p);


return 0;
}

Output: 25
Explanation: If you will see intermediate file you will find following code:


#include<stdio.h>
void main(){

int **p,q;

p=(int **)5;
q=10;
printf("%d",q+p);


return 0;
}


Explanations:

Here q pointer and p is a number.
In c
Address + number = Address

So,
New address = old address + number * Size of data type to which pointer is pointing.
= 5 + 10 * sizeof (*int)
= 5+10*2 = 25.

Note. We are assuming default pointer is near. Actually it depends upon memory model.

Pointer to function
Pointer to array of function
Pointer to array of string
Pointer to structure
pointer to union
Multi level pointer
Pointer to array of pointer to string
Pointer to three dimentional array
Pointer to two dimensional array
Sorting of array using pointer
Pointer to array of array
Pointer to array of union
Pointer to array of structure
Pointer to array of character
Pointer to array of integer
C tutorial

6 comments:

shiva said...

how many *'s can i put before pointer variable

srinivas said...

Mr.siva there is no limitation to put the *'s in pointers.because every * mark to do one speacial task.

ARCHANA said...

very nice theory with explanaition .please explain array theory with pictorial representation.thanks!

Unknown said...

I dont understand 2nd question..can someone plz explain it..??
how does q becomes a pointer inspite of being declared as a integer variable..??
thanks..

mihir said...

plz any1 explain the second question.how q is a pointer despite its declared as an normal int variable.

Raviteja Jinka said...

Great one