I am trying some programs in c face a problem with this program
can any one tell me what is the problem with this and i also want to know that when in the above case if the pointer value is incremented then will it over write the previous value address as
#include<stdio.h>
int main()
{
int a=9,*x;
float b=3.6,*y;
char c='a',*z;
printf("the value is %d\n",a);
printf("the value is %f\n",b);
printf("the value is %c\n",c);
x=&a;
y=&b;
z=&c;
printf("%u\n",a);
printf("%u\n",b);
printf("%u\n",c);
x++;
y++;
z++;
printf("%u\n",a);
printf("%u\n",b);
printf("%u\n",c);
return 0;
}
suppose that the value we got in the above program (without the increment in the pointer value )is
65524
65520
65519
and after the increment the value of the pointer is
65526(as 2 increment for the int )
65524(as 4 increment for the float )
65520(as 1 increment for the char variable )
then if in that case will the new pointer address overwrite the content of the previous address and what value be contained at the new address
First of all, I assume your calls to
printfare supposed to display the values ofx,yandz, or the addresses ofa,b, andc, correct? In that case you need to change them to:These will take into account the size of a pointer on your processor, if that is different from the size of an
int. They will also print the address in hexadecimal, which is much more common since addresses can get quite large.Assuming you’re on a platform where
intis 2 bytes (on most modern home PCsintis probably 4 now).You haven’t actually dereferenced any of the pointers here. So the memory occupied by
a,b, andcis still untouched; all you’ve done is changed whatx,y, andzare pointing to. If you were to dereference one of the pointers after incrementing it, you would be modifying memory past the variable it initially pointed to. So ifais at address 65526 decimal andintis 2 bytes:If 65528 or 65529 contained some other important data (like
borc) you’ve just corrupted your program’s state.