edited by
948 views
1 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.

```
#include
int main(){
int i=320;
char *ptr=(char *)&i;
printf("%d", "ptr);
return 0;
}
```

1 Answer

Best answer
2 2 votes

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
Position:
Show:

Related questions

1 1 vote
2 answers 2 answers
1.0k
1.0k views
ramakrushna asked Dec 26, 2021
1,007 views
I know the answer but need a good explanation for this question. Can anyone help. Thanks!What will be the output of following program?\#includeint main()\{int $\mathrm{i}...
1 1 vote
1 answers 1 answer
1.9k
1.9k views
Deepalitrapti asked Sep 20, 2018
1,930 views
Q. 22 Consider the following code int P}=0\mathrm{ ;for (i=1;i
0 0 votes
1 1 answer
533
533 views
its_vaibhav asked Jan 13, 2022
533 views
What is the output of the following c-code ? It prints the APPLIED It prints the DEILPPA It prints nothing None of the above #include#includeint main(){...
0 0 votes
1 1 answer
1.2k
1.2k views
its_vaibhav asked Jan 12, 2022
1,230 views
applied gate test seriesWhat is the output of the following c-code[ Note: Assume integer as 2 bytes] ?#include<stdio.h>int main(){ int x = 500;char *p=&x;*++p=2;printf(“...