Redirected
retagged by
1,815 views
2 votes
2 votes

Consider the following C code

int main()
{
   int a = 300;    
   char *b = (char *)&a;
   *++b = 2;
   printf("%d ",a);
   return 0;
}

Consider the size of int as two bytes and size of char as one byte. Predict the output of the following code . Assume that the machine is little-endian.

retagged by

3 Answers

Best answer
3 votes
3 votes

I think the output will be: 556

Since you mentioned in the question that the machine is little-endian, a will be stored in the little-endian form. 

a = 300 i.e. 00000001 00101100 will be stored like this - 

00101100 00000001

And assume that the address of each byte is:

100 101

Now, since "b" is a char pointer and size of char is 1 byte, b will only point to the first byte of a, i.e b = 100

a = 300; // Stored at 100, 101
char* b = (char*) &a; // b = 100
*++b = 2; // *(++b) = 2
// This means increment 'b' and then assign 2 at *b
// i.e. value at 101 = 2 (00000010)

Now, memory representation of a becomes like this - 

00101100 00000010

i.e. a = 00000010  00101100 => 556

 Hope this helps and I'd really appreciate if people point out any mistakes in my answer.

selected by
5 votes
5 votes

Bitwise the variable 'a' will look like: (Address of a starts from the right end )

PS: For big-endian the second byte above will have come first.

After *(++b) = 2, b will increment by size of the pointer type -- which is size of char here -- 1 byte as per pointer athematic. And the variable 'a' will look like

Note that second byte has value 2 now.

Ans: 556.

edited by

Related questions

7 votes
7 votes
2 answers
4
sourav. asked Jul 3, 2016
7,437 views
What will be output of the following program? Assume that you are running this program in little-endian processor.#include<stdio.h int main() { short a=320; char *ptr; pt...