Reputation: 23
I have the following program:
#include<stdio.h>
int main()
{
int i =257;
int *iptr =&i;
printf("%d%d",*((char*)iptr),*((char*)iptr+1));
return 0;
}
The output is:
1 1
I am not able to understand why the second value is 1
.
Please explain.
Upvotes: 2
Views: 146
Reputation: 2166
257 hexadecimally as 4 bytes = 0x00000101, which on Intel machines is stored in memory as 01 01 00 00. iptr points to the first 01, and iptr+1 to the second.
Upvotes: 2
Reputation: 26060
Because 257 in binary is 00000001 00000001
: So both the first and the second bytes representing it are set to 1.
(char*)iptr
is the char
(thus 1 byte) pointed by iptr
, and (char*)iptr+1
is the next byte.
Upvotes: 5
Reputation: 279215
Same reason the first value is coming out 1. You're accessing a single byte at a time from an int. Since 257 is 0x0101
, the two least significant bytes each contain the value 1.
Probably your int is 4 bytes long and stored little-endian, although I suppose it could be 2 bytes long with either endian-ness.
Upvotes: 6