599 views

4 Answers

Best answer
3 votes
3 votes
*p is passed to printf and only inside the printf "%d" comes in to play. So, if we pass only a byte for 'char' and we try to print 4 bytes for 'int' (assuming 32 bit int), we might think result is undefined.

But, C standard says that char is indeed passed as int (as most architecture feature revolve around the size of int). And while converting from char to int, sign extension is used- meaning sign bit is used for all higher order bits. Thus 255 here would be passed to printf as 2^32 - 1 (all 1's). Now, %d gives -1, %u gives 2^32 -1 and %c would give the character corresponding to (2^32 - 1) mod 256 = 255. (actually %c considers just the lower 8 bits and hence mod 256).

But we shouldn't use '%f' and it will give neither the int value converted to float nor the floating point representation corresponding to that value. It'll just give garbage value on most occasion as printf would then be using floating point register to read the value. C standard clearly says this- if the format specifiers are not matching with passed arguments, behaviour is undefined. But character and integer are an exception, as in C character is just a 8 bit integer.

Also, here little endian and big endian would give same result.

(An advise- if you are learning C stuffs by running code, never use online compilers).
selected by
1 votes
1 votes
The answ depends on the arcitecture u are using and most probably it will output -1 now the logic is see that when u see the type of the pointer is character hence it specifies that the pointer must access 8 bits of a particular location now those 8 bits on little endian actually shows the last 8 bits since representation of 255 would be (0...8 time ) (0...8 time ) (0...8 time ) (1...8 time ) now the pointer will point to these last 8 bits now since they all are 1's and we are using %d format specifer hence it would be treated as signed now signed means MSB here is 1 hence negative now for calculating its magintude complement all bits and then add 1 to it the magnitude would be 1 hence op would be -1 ,

It may give compile time error on some compilers and warning on some compilers.
0 votes
0 votes
It will give you run-time error.*p is of character type and while printing you are using %d(integer type).

Related questions

7 votes
7 votes
3 answers
1
Parshu gate asked Nov 20, 2017
741 views
What is the output of the following program?#include<stdio.h int main() { int array[]={10, 20, 30, 40}; printf(“%d”, -2[array]); return 0; }$-60$$-30$$60$Garbage valu...
3 votes
3 votes
1 answer
3
Parshu gate asked Nov 13, 2017
1,380 views
main( ){int n[3][3] = {2, 4, 3,6, 8, 5,3, 5, 1} ;printf ( "\n%d %d %d", *n, n[3][3], n ) ;}
0 votes
0 votes
2 answers
4
Akash Mishra asked Jul 7, 2017
542 views
What is the value of F(n, m)?Function F(n, m : integer) : integer; begin if(n <= 0) or (m <= 0) then F:=1 else F := F(n-1, m) + F(n, m-1); end;