Incrementing pointers in c

Address + Number= Address

Address - Number= Address


Address++ = Address

Address-- = Address


++Address = Address

--Address = Address


If we will increment or decrement a pointer result will be an address which and new address can be calculated by following formula:


Examples:

(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
Post a Comment