2

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.

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

1 Comment

Keep in mind this is only true if your integer is two bytes or if you are little-endian. Otherwise it may be stored as 0x00,0x00,0x01,0x01 and you would get 0 0 as the output.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.