in Programming in C
474 views
1 vote
1 vote

What is the output of the following c-code?

  1. 320
  2. 1
  3. 64
  4. Compiler Error

What should be ans for this one. This program will compiler error right?(invalid operands to binary ) Even i checked in Compiler by running this code. How the ans given by them is 64. Can anyone help me out. Am i missing something.

in Programming in C
474 views

1 comment

Ans C.

i=1010000000 , take first 8 bit from LSB = 10000000=64 because of char pointer.
2
2

1 Answer

2 votes
2 votes
Best answer

Quite a few things are working together to give the result $64$

  • The value $320=0\text{x}0140$ is in binary $101000000 = 00000001$ $01000000$ 
  • Your computer is more likely to be using little endian than big endian.
  • The platforms that considered big endian are: AIX, HP-UX, IBM mainframe, Macintosh, and Solaris.
  • The platforms that considered little endian are: AXP/VMS, Digital UNIX, Intel ABI, OS/2, VAX/VMS, and Windows.
  • So if address pointed by $\&i$ is $2000$,
    • the byte at $2000$ is $01000000$,
    • the byte at $2001$ is $00000001$
    • If your system assigns more than $2$ bytes for type $int$ , the bytes from $2002$ onwards would be zero.
  • Now at line 5, $\&i$ gives address pointer for address 2000. It is type casted into character pointer by use of (char *) type casting and char *ptr is initialized with this value.
  • At line 6, *ptr gives binary value $(01000000)$ of 1 byte long character pointed by pointer ptr. The use %d in printf causes implicit type conversion of that value $(01000000)$. hence it is shown as integer value $64$.

The same results can be obtained using :

#include <stdio.h>
int main()
{
   int i=320;
   int *ptr=&i;
   printf("%d",*(char *)ptr);
   return 0;
}

or

#include <stdio.h>
int main()
{
   int i=320;
   int *ptr=&i;
   printf("%d",(char)*ptr);
   return 0;
}

 

selected by

1 comment

@Zack Fair Thank you so much man!

0
0

Related questions

1 vote
1 vote
1 answer
2
Deepalitrapti asked in Algorithms Sep 20, 2018
822 views
Deepalitrapti asked in Algorithms Sep 20, 2018
822 views