Reputation: 13
What will be the output of the following code?
#include<stdio.h>
int main()
{
int a[4]={4096,2,3,4};
char *p;
p=a;
printf("\n %d",(int)*(++p));
return 0;
}
sizeof int = sizeof(void*) = 4 bytes
According to me the output should be 16 on a little endian machine and 0 on a big endian machine. Am I right?
Upvotes: 1
Views: 467
Reputation: 279405
4096 is 0x1000
, so (once you get it to compile) you'd expect 16 with a little-endian representation, and 0 with a big-endian representation unless int
is 24 bits wide (that would give 16).
All this assuming CHAR_BIT == 8
, and no funny-business with padding bits. The edit with sizeof(int) == 4
also rules out the 24 bit int
under those assumptions.
Upvotes: 1
Reputation: 400129
4096 (hex 0x1000) will be represented in memory (assuming 8-bit bytes, which is quite common nowadays) as either:
[0x00, 0x00, 0x10, 0x00] (big-endian)
or
[0x00, 0x10, 0x00, 0x00] (little-endian)
Since you're printing it out using %d, which expects integers, but passing a dereferenced character pointer value (i.e., a char
) and incrementing the pointer before dereferencing it, you will print either 0x00 or 0x10, which is 16 in decimal. You will probably need to add some cast to allow the p = a
statement, since you're mixing types rather freely.
So yes, I think you're right.
Upvotes: 1