Tuesday, 12 June 2012

POINTERS TURORIAL


Understanding pointers in c


Introduction to pointers in c



Pointer is a variable just like other variables of c but only difference is unlike the other variable it stores the memory address of any other variables of c. This variable may be type of int, char, array, structure, function or any other pointers. For examples:

(1)
Pointer p which is storing memory address of a int type variable:

int i=50;
int *p=&i;

(2)
Pointer p which is storing memory address of an array:

int arr[20];
int (*p)[20]=&arr;

(3)
Pointer p which is storing memory address of a function:

char display(void);
char(*p)(void)=&display;

(4)
Pointer p which is storing memory address of struct type variable:

struct abc{
int a;
float b;
}var;
struct abc *p=&var;

What is pointer in c programming?


Explain pointers in c

Pointer is a user defined data type which creates special types of variables which can hold the address of primitive data type likecharintfloatdouble or user defined data type like function, pointer etc. or derived data type like array, structure, union,enum.
Examples:
int *ptr;
int (*ptr)();
int (*ptr)[2];
In c programming every variable keeps two type of value.
1. Contain of variable or value of variable.
2. Address of variable where it has stored in the memory.
(1) Meaning of following simple pointer declaration and definition:
int a=5;
int * ptr;
ptr=&a;

Explanation:

About variable a:
1. Name of variable : a
2. Value of variable which it keeps: 5
3. Address where it has stored in memory : 1025 (assume)

About variable ptr:
4. Name of variable : ptr
5. Value of variable which it keeps: 1025
6. Address where it has stored in memory : 5000 (assume)

Pictorial representation:


Note: A variable where it will be stored in memory is decided by operating system. We cannot guess at which location a particular variable will be stored in memory.

(2) Meaning of following pointer declaration and definition:
int a=50;
int *ptr1;
int **ptr2;
ptr1=&a;
ptr2=&pt1;
Explanation: 

About variable a:
1. Name of variable : a
2. Value of variable which it keeps: 50
3. Address where it has stored in memory : 5000 (assume)

About variable ptr1:
4. Name of variable : ptr1
5. Value of variable which it keeps: 5000
6. Address where it has stored in memory : 9000 (assume)

About variable ptr2:
7. Name of variable : ptr2
8. Value of variable which it keeps: 9000
9. Address where it has stored in memory : 9555 (assume)

Pictorial representation of above pointer declaration and definition:

Note:
* is known as indirection operator which gives content of any variable.
& is known as reference operator which gives address where variable has stored in memory.
Cancellation rule of above two operators:
* and & operators always cancel to each other i.e.
*&p=p

But it is not right to write:
&*p=p

Simple example:
What will be output of following c program?
#include<stdio.h>
int main(){

    int x=25;
    int *ptr=&x; //statement one
    int **temp=&ptr; //statement two
    printf(“%d %d %d”.x.*ptr,**temp);
    return 0;
}
Output: 25 25 25
Explanation:
As we know value of variable x is 25.
*ptr= *(&x) //from statement one
=*&x
=x //using cancellation rule
=25
**temp= **(&ptr)=*(*&ptr)=*ptr=*(&x)=*&x=x=25

How to read complex pointers in C Programming?



Rule 1. Assign the priority to the pointer declaration considering precedence and associative according to following table.

Where

(): This operator behaves as bracket operator or function operator.

[]: This operator behaves as array subscription operator.

*: This operator behaves as pointer operator not as multiplication operator.

Identifier: It is not an operator but it is name of pointer variable. You will always find the first priority will be assigned to the name of pointer.

Data type: It is also not an operator. Data types also includes modifier (like signed int, long double etc.)

You will understand it better by examples:

(1) How to read following pointer?

char (* ptr)[3]
Answer:

Step 1: () and [] enjoys equal precedence. So rule of associative will decide the priority. Its associative is left to right So first priority goes to ().



Step 2: Inside the bracket * and ptr enjoy equal precedence. From rule of associative (right to left) first priority goes to ptr and second priority goes to *.

Step3: Assign third priority to [].

Step4: Since data type enjoys least priority so assign fourth priority to char.

Now read it following manner:

ptr is pointer to such one dimensional array of size three which content char type data. 

(2) How to read following pointer?
float (* ptr)(int)
Answer:

Assign the priority considering precedence and associative.




Now read it following manner:

ptr is pointer to such function whose parameter is int type data and return type is float type data.

Rule 2: Assign the priority of each function parameter separately and read it also separately.
Understand it through following example.

(3) How to read following pointer?
void (*ptr)(int (*)[2],int (*) void))
Answer:

Assign the priority considering rule of precedence and associative.



Now read it following manner:

ptr is pointer to such function which first parameter is pointer to one dimensional array of size two which content int type data and second parameter is pointer to such function which parameter is void and return type is int data type and return type is void

(4) How to read following pointer?

int ( * ( * ptr ) [ 5 ] ) ( )
Answer:

Assign the priority considering rule of precedence and associative.



Now read it following manner:
ptr is pointer to such array of size five which content are pointerto such function which parameter is void and return type is int type data.

(5) How to read following pointer?
double*(*(*ptr)(int))(double **,char c)
Answer:


Assign the priority considering rule of precedence and associative.

Now read it following manner:
ptr is pointer to function which parameter is int type data and return type is pointer to function which first parameter is pointer to pointer of double data type and second parameter is char type data type and return type is pointer to double data type.

(6) How to read following pointer?
unsigned **(*(*ptr)[8](char const *, ...)
Answer:

Assign the priority considering rule of precedence and associative.

Now read it following manner:
ptr is pointer to array of size eight and content of array ispointer to function which first parameter is pointer to character constant and second parameter is variable number of arguments and return type is pointer to pointer of unsigned int data type.

Arithmetic operation with pointer in c programming





Rule 1: Addition arithmetic with pointers

Address + Number= Address
Address - Number= Address

Address++ = Address
Address-- = Address

++Address = Address
--Address = Address

If we will add or subtract a number from an address result will also be an address.
New address will be:










(1)What will be output of following c program?


#include<stdio.h>

int main(){

int *ptr=( int *)1000;

ptr=ptr+1;
printf(" %u",ptr);


return 0;
}



Output: 1002



(2)What will be output of following c program?


#include<stdio.h>

int main(){

double *p=(double *)1000;

p=p+3;
printf(" %u",p);


return 0;
}

Output: 1024



(3)What will be output of following c program?


#include<stdio.h>

int main(){

float array[5]={1.1f,2.2f,3.3f};
float(*ptr)[5];

ptr=&array;
printf("%u",ptr);

ptr=ptr+1;
printf(" %u",ptr);


return 0;
}

Output: 1000 1020



(4)What will be output of following c program?


#include<stdio.h>

typedef struct abc{
int far*a;
double b;
unsigned char c;
}ABC;

int main(){

ABC *ptr=(ABC *)1000;

ptr=ptr+2;
printf(" %u",ptr);


return 0;
}

Output: 1026



(5)What will be output of following c program?


#include<stdio.h>

typedef union abc{
char near*a;
long double d;
unsigned int i;
}ABC;

int main(){

ABC *ptr=(ABC *)1000;

ptr=ptr-4;
printf(" %u",ptr);


return 0;
}

Output: 960





(6)What will be output of following c program?


#include<stdio.h>

float * display(int,int);
int max=5;

int main(){

float *(*ptr)(int,int);

ptr=display;

(*ptr)(2,2);
printf("%u",ptr);

ptr=ptr+1;
printf(" %u",ptr);


return 0;
}

float * display(int x,int y){
float f;
f=x+y+max;
return &f;
}

Output: Compiler error





Rule 2: Difference arithmetic with pointers

Address - Address=Number

If you will subtract two pointers result will be a number but number will not simple mathematical subtraction of two addresses but it follow following rule:
If two pointers are of same type then:






Consider following example:


#include<stdio.h>

int main(){

int *p=(int *)1000;
int *temp;

temp=p;
p=p+2;

printf("%u %u\n",temp,p);
printf("difference= %d",p-temp);


return 0;
}

Output: 1000 1004
Difference= 2

Explanation:
Here two pointer p and temp are of same type and both are pointing to int data type varaible.
p-temp = (1004-1000)/sizeof(int)
=4/2
=2





(1)What will be output of following c program?


#include<stdio.h>

int main(){

float *p=(float *)1000;
float *q=(float *)2000;

printf("Difference= %d",q-p);


return 0;
}

Output: Difference= 250

Explanation:
q-p=(2000-100)/sizeof(float)
=1000/4
=250

(2)What will be output of following c program?


#include<stdio.h>

struct abc{
signed char c;
short int i;
long double l;
};

int main(){

struct abc *p,*q;

p=(struct abc *)1000;
q=(struct abc *)2000;

printf("Difference= %d",q-p);


return 0;
}

Output: Difference= 76

Explanation:

q-p=(2000-1000)/sizeof(struct abc)
=1000/(1+2+10)
=1000/13
=76



(3)What will be output of following c program?


#include<stdio.h>

typedef union xxx{
char far * c;
const volatile i;
long int l;
}XXX;

int main(){

XXX *p,*q;

p=(XXX *)1000;
q=(XXX *)2000;

printf("Difference= %d",q-p);


return 0;
}

Output: Difference= 250

Explanation:
q-p=(2000-100)/max(4,2,4)
=1000/4
=250



(4)What will be output of following c program?


#include<stdio.h>

int main(){

const volatile array[4]={0};
const volatile(*p)[4]=&array;
const volatile(*q)[4]=&array;

q++;
q++;

printf("%u %u\n",p,q);
printf("Difference= %d",q-p);


return 0;
}

Output: 1000 1016 (assume)
Difference= 2

Explanation:
q-p=(1016-1000)/sizeof(const volatile)
= 16/ (2*4)
=2





Rule 3: Illegal arithmetic with pointers

Address + Address=Illegal
Address * Address=Illegal
Address / Address=Illegal
Address % Address=Illegal

What will be output of following c program?


#include<stdio.h>

int main(){

int i=5;
int *p=&i;
int *q=(int *)2;

printf("%d",p+q);


return 0;
}

Output: Compiler error

Rule 4: We can use relation operator and condition operator between two pointers.

a. If two pointers are near pointer it will compare only its offset address.



What will be output of following c program?


#include<stdio.h>

int main(){

int near*p=(int near*)0x0A0005555;
int near*q=(int near*)0x0A2115555;

if(p==q)
printf("Equql");
else
printf("Not equal");

    return 0;
}

Output: Equal





b. If two pointers are far pointer it will compare both offset and segment address.

What will be output of following c program?


#include<stdio.h>

int main(){

int far*p=(int far*)0x0A0005555;
int far*q=(int far*)0x0A2115555;

if(p==q)
printf("Equql");
else
printf("Not equal");

    return 0;
}

Output: Not equal



c. If two pointers are huge pointer it will first normalize into the 20 bit actual physical address and compare to its physical address.



What will be output of following c program?


#include<stdio.h>

int main(){

int huge*p=(int huge*)0x0A0005555;
int huge*q=(int huge*)0x0A2113445;

if(p==q)
printf("Equql");
else
printf("Not equal");

    return 0;
}

Output: Equal



Rule 5: Bit wise arithmetic with pointers


We can perform bit wise operation between two pointers like

Address & Address=Illegal
Address | Address=Illegal
Address ^ Address=Illegal
~Address=Illegal





What will be output of following c program?


#include<stdio.h>

int main(){

int i=5,j=10;
int *p=&i;
int *q=&j;

printf("%d",p|q);


return 0;
}

Output: Compiler error



Rule 6: We can find size of a pointer using sizeof operator.

What will be output of following c program?


#include<stdio.h>

int main(){

int near*far*huge* p;

printf("%d",sizeof(p));
printf(" %d",sizeof(*p));
printf(" %d",sizeof(**p));


return 0;
}

Output: 4 4 2

Pointer to function in c programming

Function pointer definition:  A pointer which keeps address of a function is known as function pointer.  


Examples of function pointers in c:


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


#include<stdio.h>
int * function();
int main(){
auto int *x;
int *(*ptr)();

ptr=&function;
x=(*ptr)();
printf("%d",*x);


return 0;
}
int *function(){
static int a=10;
return &a;
}

Output: 10
Explanation: Here function is function whose parameter is void data type and return type is pointer to int data type.
x=(*ptr)()
=> x=(*&functyion)() //ptr=&function
=> x=function() //From rule *&p=p
=> x=&a
So, *x = *&a = a =10

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


#include<stdio.h>
int find(char);
int(*function())(char);
int main(){

int x;
int(*ptr)(char);

ptr=function();
x=(*ptr)('A');
printf("%d",x);


return 0;
}
int find(char c){
return c;
}
int(*function())(char){
return find;
}

Output: 65
Explanation: Here function whose name is function which passing void data type and returning another function whose parameter is char data type and return type is int data type.

x=(*ptr)(‘A’)
=> x= (*function ()) (‘A’) //ptr=function ()
//&find=function () i.e. return type of function ()
=> x= (* &find) (‘A’)
=> x= find (‘A’) //From rule*&p=p
=> x= 65

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


#include<stdio.h>
char * call(int *,float *);
int main(){

char *string;
int a=2;
float b=2.0l;
char *(*ptr)(int*,float *);

ptr=&call;
string=(*ptr)(&a,&b);
printf("%s",string);


return 0;
}

char *call(int *i,float *j){
static char *str="c-pointer.blogspot.com";

str=str+*i+(int)(*j);
return str;
}

Output: inter.blogspot.com
Explanation: Here call is function whose return type is pointer to character and one parameter is pointer to int data type and second parameter is pointer to float data type and ptr is pointer to such function.
str= str+*i+ (int) (*j)
=”c-pointer.blogspot.com” + *&a+ (int) (*&b)
//i=&a, j=&b
=”c-pointer.blogspot.com” + a+ (int) (b)
=”c-pointer.blogspot.com” +2 + (int) (2.0)
=”c-pointer.blogspot.com” +4
=”inter.blogspot.com”

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


#include<stdio.h>
char far * display(char far*);
int main(){

char far* string="cquestionbank.blogspot.com";
char far *(*ptr)(char far *);

ptr=&display;
string=(*ptr)(string);
printf("%s",string);


return 0;
}
char far *display(char far * str){

char far * temp=str;

temp=temp+13;
*temp='\0';

return str;
}

Output: cquestionbak
Explanation: Here display is function whose parameter is pointer to character and return type is also pointer to character and ptr is its pointer.
temp is char pointer
temp=temp+13
temp=’\0’
Above two lines replaces first dot character by null character of string of variable string i.e.
"cquestionbank\0blogspot.com"
As we know %s print the character of stream up to null character.

Pointer to array of function in c

Array of function means array which content is address of function and pointer to array of function means pointer is pointing to such array.


In other word we can say pointer to array of functions is a pointer which is pointing to an array which contents are pointers to a function.


Examples of pointer to array of function:

What will be output if you will execute following code?


#include<stdio.h>
int display();
int(*array[3])();
int(*(*ptr)[3])();

int main(){
array[0]=display;
array[1]=getch;
ptr=&array;

printf("%d",(**ptr)());

(*(*ptr+1))();
return 0;
}
int display(){
int x=5;
return x++;
}

Output: 5
Explanation:

In this example:

array []: It is array of pointer to such function which parameter is void and return type is int data type.

ptr: It is pointer to array which contents are pointer to such function which parameter is void and return type is int type data.

(**ptr)() = (** (&array)) () //ptr=&array
= (*array) () // from rule *&p=p
=array [0] () //from rule *(p+i)=p[i]
=display () //array[0]=display
(*(*ptr+1))() =(*(*&array+1))() //ptr=&array
=*(array+1) () // from rule *&p=p
=array [1] () //from rule *(p+i)=p[i]
=getch () //array[1]=getch

Pointer to array of string in c programming

Pointer to array of string: A pointer which pointing to an array which content is string, is known as pointer to array of strings.


What will be output if you will execute following code?


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

char *array[4]={"c","c++","java","sql"};
char *(*ptr)[4]=&array;
printf("%s ",++(*ptr)[2]);


return 0;
}

Output: ava
Explanation:

In this example

ptr: It is pointer to array of string of size 4.

array[4]: It is an array and its content are string.
Pictorial representation:







Note: In the above figure upper part of box represent content and lower part represent memory address. We have assumed arbitrary address.

Pointer to structure in c programming



Pointer to structure: A pointer which is pointing to a structure is know as pointer to structure. 


Examples of pointers to structure:

What will be output if you will execute following code?


#include<stdio.h>

struct address{
char *name;
char street[10];
int pin;
}cus={"A.Kumar","H-2",456003},*p=&cus;

int main(){

printf("%s %s",p->name,(*p).street);


return 0;
}

OutputA.Kumar H-2
Explanation:

p is pointer to structure address.
-> and (*). Both are same thing. These operators are used to access data member of structure by using structure’s pointer.

Pointer to union in c programming

Pointer to structure: A pointer which is pointing to a structure is know as pointer to structure. 


Examples of pointers to structure:


What will be output if you will execute following code?


#include<stdio.h>

union address{
char *name;
char street[10];
int pin;
};

int main(){

union address emp,*p;

emp.name="ja\0pan";
p=&emp;

printf("%s %s",p->name,(*p).name);


return 0;
}

Output: ja ja
Explanation:
p is pointer to union address.
-> and (*). Both are same thing. These operators are used to access data member of union by using union’s pointer.
%s is used to print the string up to null character i.e. ‘\0’

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 array of pointer to string in c programming



Pointer to array of pointer to string: A pointer to an array which contents are pointer to string.


Example of Pointer to array of pointer to string:


What will be output if you will execute following code?


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

static char *s[3]={"math","phy","che"};
typedef char *( *ppp)[3];
static ppp p1=&s,p2=&s,p3=&s;
char * (*(*array[3]))[3]={&p1,&p2,&p3};
char * (*(*(*ptr)[3]))[3]=&array;

p2+=1;
p3+=2;

printf("%s",(***ptr[0])[2]);


return 0;
}

Output: che
Explanation: 

Here
ptr: is pointer to array of pointer to string.

P1, p2, p3: are pointers to array of string.

array[3]: is array which contain pointer to array of string.

Pictorial representation:

Note: In the above figure upper part of box represent content and lower part represent memory address. We have assumed arbitrary address.

As we know p[i]=*(p+i)

(***ptr[0])[2]=(*(***ptr+0))[2]=(***ptr)[2]
=(***(&array))[2] //ptr=&array
=(**array)[2] //From rule *&p=p
=(**(&p1))[2] //array=&p1
=(*p1)[2]
=(*&s)[2] //p1=&s
=s[2]=”che”
++(*ptr)[2]
=++(*&array)[2] //ptr=&array
=++array[2]
=++”java”
=”ava” //Since ptr is character pointer so it
// will increment only one byte

Note: %s is used to print stream of characters up to null (\0) character.

Pointer to three dimensional array in c programming



Examples of pointers to 3 dimensional array:


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

const array[2][3][3]={0,1,2,3,4,5,6,7,8,9,10,11,12};
int const (*ptr)[2][3][3]=&array;

printf("%d ",*(*(*ptr)[1]+2));


return 0;
}

Output: 11
Explanation:

In this example:
array [2][3][3]:It is three dimensional array and its content are constant integers.
ptr: It is pointer to such three dimensional array whose content are constant integer.

Pictorial representation:

Note: In the above figure upper part of box represent content and lower part represent memory address. We have assumed arbitrary address.

*(*(*ptr) [1] +2)
=*(*(*&array) [1] +2)
=*(*array [1] +2)
=*(array [1] [0] +2)
=array [1] [0] [2] 

I.e. array element at the 1*(3*3) +0(3) + 2=11th position starting from zero which is 11.

Pointer to two dimensional array in c programming

Examples of pointers to 2 dimensional array:


What will be output if you will execute following code?


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

long array[][3]={7l,14l,21l,28l,35l,42l};
long int (*ptr)[2][3]=&array;

printf("%li ",-0[1[0[ptr]]]);


return 0;
}

Output: -28
Explanation:

-0[1[0[ptr]]]
=-1[0[ptr]][0] //From rule array[i]=i[array]
=-0[ptr][1][0]
=-ptr [0] [1] [0]
=-*ptr [0] [1] //From rule array[i]=*(array+i)
=-*(&array) [0] [1]
=-(&array) [0] [1][0]
=-(*&array)[1][0] //From rule *&p=p
=-array[1][0]

array[1][0] means 1*(3)+ 0 = 3rd element of array starting from zero i.e. 28

sorting of array using pointer in c

int main(){
   int  i,j,temp1,temp2;
   int arr[8]={5,3,0,2,12,1,33,2};
   int *ptr;
   for(i=0;i<7;i++){
     for(j=0;j<7-i;j++){
if(*(arr+j)>*(arr+j+1)){
        ptr=arr+j;
        temp1=*ptr++;
        temp2=*ptr;
        *ptr--=temp1;
        *ptr=temp2;
}
      }
   }

   for(i=0;i<8;i++)
     printf(" %d",arr[i]);
}

Output: 0 1 2 2 3 5 12 33

Pointer to array of array in c



Examples of pointer to array of array in c:


What will be output if you will execute following code?


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

static float farray[][3]={0.0f,1.0f,2.0f,3.0f,4.0f,5.0f,6.0f,7.0f,8.0f};
float (*array[3])[3]={&farray[0],&farray[1],&farray[2]};
float (*(*ptr)[])[3]=&array;

printf("%f ",2[(*(**ptr+1))]);


return 0;
}

Output: 5.000000
Explanation:

In this example:

farray [][3]: It is two dimension array and its content are float constants. 

array [3]:It is one dimension array and its content are address of such one dimension array which content are float constant.

ptr: It is pointer to one dimension array which content are address of such one dimension array which content are float constant. 

Pictorial representation:
Note: In the above figure upper part of box represent content and lower part represent memory address. We have assumed arbitrary address.

2[(*(**ptr+1))]
= (*(**ptr+1)) [2]
= (*(**&array+1)) [2]
= (*(*array+1)) [2]
= (*(array [0] +1)) [2]
= (*(&farray [0] +1)) [2]
=&farray [0] [1] [2]
=*&farray [1] [2]
=farray [1] [2]

It is 1*(3) +2=5th element of farray starting from zero which is 5.0f

Pointer to array of union in c programming

Pointer to array of union:  A pointer to an array which contents is pointer to union is known as pointer to array of union.



What will be output if you will execute following code?

union emp{
char *name;
int id;
};

int main(){

static union emp e1={"A"},e2={"B"},e3={"C"};
union emp(*array[])={&e1,&e2,&e3};
union emp(*(*ptr)[3])=&array;

printf("%s ",(*(*ptr+2))->name);


return 0;
}

Output: C
Explanation:

In this example:
e1, e2, e3: They are variables of union emp.

array []:It is one dimensional array of size thee and its content are address of union emp.

ptr: It is pointer to array of union. 

(*(*ptr+2))->name
=(*(*&array+2))->name //ptr=&array
=(*(array+2))->name //from rule *&p=p
=array[2]->name //from rule *(p+i)=p[i]
=(&e3)->name //array[2]=&e3
=*(&e3).name //from rule ->= (*).
=e3.name //from rule *&p=p
=”C”

Pointer to array of structure in c programming

Pointer to array of structure: A pointer to an array which contents are pointer to structure is know pointer to array of structure.

What will be output if you will execute following code?


#include<stdio.h>

struct emp{
char *name;
int id;
};

int main(){

static struct emp e1={"A",1},e2={"B",2},e3={"C",3};
struct emp(*array[])={&e1,&e2,&e3};
struct emp(*(*ptr)[3])=&array;

printf("%s %d",(**(*ptr+1)).name,(*(*ptr+1))->id);


return 0;
}

Output: B 2
Explanation:

(**(*ptr+1)).name
=(**(*&array+1)).name //ptr=&array
=(**(array+1)).name //from rule *&p =p
=(*array[1]).name //from rule *(p+i)=p[i]
=(*&e2).name //array[1]=&e2
=e2.name=”B” //from rule *&p =p
(*(*ptr+1))->id
=(**(*ptr+1)).id //from rule -> = (*).
=e2.id=2

Pointer to array of character in c

Pointer to array of character: A pointer to such an array which contents is character constants is known as pointer to array of character constant.

What will be output if you will execute following code?


#include<stdio.h>
char display(char (*)[]);

int main(){

char c;
char character[]={65,66,67,68};
char (*ptr)[]=&character;

c=display(ptr);
printf("%c",c);


return 0;
}

char display(char (*s)[]){
**s+=2;
return **s;
}

Output: C
Explanation: Here function display is passing pointer to array of characters and returning char data type.

**s+=2
=>**s=**s+2
=>**ptr=**ptr+2 //s=ptr
=>**&character= **&character+2 //ptr=&character
=>*character=*character+2 //from rule *&p =p
=>character[0]=character[0]+2 //from rule *(p+i)=p[i]
=>character [0] =67
**s=character [0] =67

Note: ASCII value of ‘C’ is 67

Pointer to array of integer in c




Pointer to array of integers: A pointer to such an array which contents are integer numbers is known as pointer to array of integer.


What will be output if you will execute following code?


#include<stdio.h>

int main(){

static int i,j,k;
int *(*ptr)[];
int *array[3]={&i,&j,&k};

ptr=&array;
j=i+++k+10;
++(**ptr);

printf("%d",***ptr);


return 0;
}

Output: 10
Explanation:

In this example:

array []: It is array of size three and its content are address of integer.

ptr: It is pointer to array which content are address of integer.

Pictorial representation above declaration:







Note: In the above figure upper part of box represent content and lower part represent memory address. We have assumed arbitrary address.

j=i+++k+10
=i++ + k+10
=0 +0 +10=10

***ptr = *** (&array) //ptr=&array
= **array //From rule *&p=p
//From rule array [0] =*(array+0) and ++ (**ptr)
=*array [1]
=*&j
=j
=10



What will be output if you will execute following code?


#include<stdio.h>

int main(){

int i,j,k;
int *(*ptr)[];
int *array[3]={&i,&j,&k};

ptr=&array;
j=i+++k+10;
++(**ptr);

printf("%d",***ptr);


return 0;
}

Output: Compiler error
Explanation: Address of auto variable cannot be member of an array.



(1) Pointer to function
(2) Pointer to array
a. Pointer to array of integer
b. Pointer to array of function
c. Pointer to array of character
d. Pointer to array of structure
e. Pointer to array of union
f. Pointer to array of array
g. Pointer to two dimensional array
h. Pointer to three dimensional array
i. Pointer to array of string
j. Pointer to array of pointer to string
(3) Pointer to structure
(4) Pointer to union
(5) Multilevel pointers



Generic pointer in c programming

Generic pointer:

void pointer in c is known as generic pointer. Literal meaning of generic pointer is a pointer which can point type of data.

Example:

void *ptr;
Here ptr is generic pointer.

Important points about generic pointer in c?

1. We cannot dereference generic pointer.


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

void *ptr;
printf("%d",*ptr);


return 0;
}

Output: Compiler error

2. We can find the size of generic pointer using sizeof operator.

#include <string.h>
#include<stdio.h>
int main(){
void *ptr;
printf("%d",sizeof(ptr));


return 0;
}

Output: 2
Explanation: Size of any type of near pointer in c is two byte.

3. Generic pointer can hold any type of pointers like char pointer, struct pointer, array of pointer etc without any typecasting.

Example:


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

char c='A';
int i=4;
void *p;
char *q=&c;
int *r=&i;

p=q;
printf("%c",*(char *)p);

p=r;
printf("%d",*(int *)p);


return 0;
}

Output: A4

4. Any type of pointer can hold generic pointer without any typecasting.

5. Generic pointers are used when we want to return such pointer which is applicable to all types of pointers. For example return type of malloc function is generic pointer because it can dynamically allocate the memory space to stores integer, float, structure etc. hence we type cast its return type to appropriate pointer type.

Examples:
1.

char *c;
c=(char *)malloc(sizeof(char));

2.
double *d;
d=(double *)malloc(sizeof(double));

3.
Struct student{
char *name;
int roll;
};
Struct student *stu;
Stu=(struct student *)malloc(sizeof(struct student));

NULL pointer in c programming

NULL pointer:

Literal meaning of NULL pointer is a pointer which is pointing to nothing. NULL pointer points the base address of segment.

Examples of NULL pointer:

1. int *ptr=(char *)0;
2. float *ptr=(float *)0;
3. char *ptr=(char *)0;
4. double *ptr=(double *)0;
5. char *ptr=’\0’;
6. int *ptr=NULL;

What is meaning of NULL?

NULL is macro constant which has been defined in the heard file stdio.h, alloc.h, mem.h, stddef.h and stdlib.h as
#define NULL 0

Examples:

What will be output of following c program?

#include <stdio.h>

int main(){
if(!NULL)
printf("I know preprocessor");
else
printf("I don't know preprocessor");

    return 0;
}

Output: I know preprocessor
Explanation:
!NULL = !0 = 1

In if condition any non zero number mean true.

What will be output of following c program?

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

int i;
static int count;

for(i=NULL;i<=5;){
count++;
i+=2;
}

printf("%d",count);


return 0;
}

Output: 3

What will be output of following c program?

#include <stdio.h>

int main(){

#ifndef NULL
#define NULL 5
#endif

printf("%d",NULL+sizeof(NULL));


return 0;
}

Output: 2
Explanation:

NULL+sizeof(NULL)
=0+sizeoof(0)
=0+2 //size of int data type is two byte.

We cannot copy any thing in the NULL pointer.

Example:

What will be output of following c program?

#include <string.h>
#include <stdio.h>

int main(){

char *str=NULL;

strcpy(str,"c-pointer.blogspot.com");
printf("%s",str);


return 0;
}

Output: (null)

Wild pointer in c programming language.

Wild pointer:

A pointer in c which has not been initialized is known as wild pointer.

Example:

What will be output of following c program?


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

int *ptr;

printf("%u\n",ptr);
printf("%d",*ptr);


return 0;
}


Output: 


Any address
Garbage value

Here ptr is wild pointer because it has not been initialized.

There is difference between the NULL pointer and wild pointer. Null pointer points the base address of segment while wild pointer doesn’t point any specific memory location.

3. File pointer






No comments:

Post a Comment