-3

During some trial and error, came across this. It is outputting 513 as the value, cant figure out why.

int a;
char *x;
x =(char *) &a;
a = 512;
x[0]=1;
x[1]=2;
printf("%d\n ",a); 
John Kugelman
  • 349,597
  • 67
  • 533
  • 578

1 Answers1

1

On a typical x86 platform an int is four bytes wide and is stored little endian. Little endian means the bytes are stored in reverse, least significant to most significant. The number 512 is represented in memory as 2 × 28, or:

{ 0x00, 0x02, 0x00, 0x00 }
// LSB              MSB
// 2^0  2^8   2^16  2^24

After the two assignments you have:

{ 0x01, 0x02, 0x00, 0x00 }
// LSB              MSB
// 2^0  2^8   2^16  2^24

Converting these four bytes back to decimal you have 1 × 20 + 2 × 28 = 1 + 512 = 513.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578