I have following code
int main()
{
int arr[3] = {2, 3};
char *p;
p = arr;
p = (char *)((int*)(p));
printf("%d, ", *p);
p++;
p = (int*)(p+1);
printf("%d", *p);
return 0;
}
o/p-2,0
but I want to know how it is printing 0 in second printf ,I know all stuffs about little-endian as in memory of 4 byte integer how these elements are stored, as follows
00000010 00000000 0000000 00000000 00000011 00000000 00000000 00000000
so, during the first printf we got 2 as answer but during second printf the pointer is at second byte which is 0 but it is now a integer pointer but how it is printing 0,as it has to check for upto 4 bytes of memory then it has to print the whole data upto 4 byte.
I thought will be 3 as upto 4 byte it will print.
what i want is how the integer data is printing by printf,can any one tell this.
The type of the pointer
pdoes not change with either of the two:p = (char *)((int*)(p));p = (int*)(p+1);.It still remains a pointer to a
char.The cast only works to alter values (or types) in expressions. It applies to copies of values extracted from variables but does not modify those variables. Once the expression is over, the cast is gone with the value copy it was associated with.
Example:
Here the value of
c, -1, is converted/cast to the typeunsigned char. If chars are 8-bit, the result of(unsigned char)-1is 255 and this value is of typeunsigned char, which then gets converted tointand assigned toi.cdoes not change anyhow in the above process.Example 2:
Here
puis converted/cast to type pointer tounsigned char. That conversion does not modify the variablepu, it only changes a copy of its value. And here it just changes the type of the copy, not the actual address, contained in the pointer variable. And then this copy of the address is assigned topc. The cast is needed to avoid compiler warnings/errors, because the compiler has all the rights to “wonder” what is going on here and if there might be a programming mistake.Now both
puandpcpoint to the same location, the beginning of the variableu. But they have different types, one points to anunsigned charand the other, to anunsigned int.And so if you dereference
puandpc, you’ll get different values and those will be of different types as well.Likewise, if you do pointer arithmetic on the two pointers, for example, adding 1 to each, they will advance to point to different locations in memory.
pu+1will point to the location right after the end ofuandpc+1will point to the 2ndunsigned charfrom the beginning ofu.Are you starting to see it?