Incrementing pointers in c

Address + Number= Address

Address - Number= Address


Address++ = Address

Address-- = Address


++Address = Address

--Address = Address


When a pointer is incremented or decremented in C, the outcome is a new memory address, and this new address can be computed based on the size of the data type the pointer is associated with. 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

No comments: