673 views
1 votes
1 votes
#include <stdio.h>

int main() {
    
int i = 258;
int *iptr = &i;

printf("%d",*(char*)iptr);
printf("%d",*(char*)iptr+1);

    
}

Please explain the solution.

2 Answers

Best answer
3 votes
3 votes

The output of the above code will vary from machine to machine, i.e. if the machine uses Little Endian system, the output will be different than a machine using Big Endian system. Little Endian and  Big Endian are different ways of storing multi-byte data in memory.

Consider a number in base 10 : 4,053,122,096 and it's binary representation (if integer is of 4 Bytes)- 

 Ist byte        2nd byte        3rd byte        4th byte

11110001  10010101  10111100  00110000

 

According to Little endian system, the bytes are stored in reverse order. ie, the last byte (4th byte will be store first), followed by the 3rd byte, then 2nd byte and finally the 1st byte.

In Big Endian system, the 1st byte is stored, followed by 2nd byte, then 3rd byte and finally 4th byte

The no. 4,053,122,096 will be stored in little & big endian systems as follows:

Now coming to your question:

Assuming that an integer takes 4 bytes, the representation of no. 258 in Little & Big Endian will be:

printf("%d",*(char*)iptr);

Say iptr points to memory address : 100

You are typecasting an integer pointer into a char pointer, ie. you are asking the pointer iptr just to read one byte from memory address 100. So iptr is going to read the 1st Byte from location 100.

If the machine were following Little Endian representation - 1st Byte at location 100 would have been the number 2. 

If the machine were following Big Endian representation - 1st Byte at location 100 would have been the number 0.

OUTPUT

Little Endian - 2

Big Endian - 0

 

printf("%d",*(char*)iptr+1);

According to operator precedence rules - (char *) gets 1st priority, '*' (dereferencing operator) gets 2nd priority and '+' gets last priority.

Therefore the value at address 100 is read (only the first byte will be read) and + 1 will be done at last.

ie

OUTPUT

Little Endian: 2 + 1 = 3

Big Endian: 0 + 1 = 1

 

PS: Such type of questions are not asked in GATE

 

selected by
0 votes
0 votes
first statement prints 2 as char is 1 bye ie 2^8 (256) unsigned so 258-256 =2

second statement prints 3 as first *(char*)iptr is calculated & after that 1 is added therefore 3.

Related questions

0 votes
0 votes
1 answer
2
Rohit Chakraborty asked Oct 6, 2023
470 views
What is the correct option for the blanks so that the program runs in the correct manner?I was getting the answer B
3 votes
3 votes
1 answer
3
TusharKumar asked Jan 31, 2023
517 views
answer given is 33