446 views
2 votes
2 votes

Plz provide explaination for this question....

2 Answers

4 votes
4 votes

The output will be -1.

Why?

Because, when you typecast an int address to char pointer, the pointer will assume that there will be a character value stored at that pointer's location.

511 will be stored in memory like this - 00000000 00000000 00000001 11111111

Since char can only hold 1 bytes(8 bits) on all machines, it will take only least 8 significant bits of 511, i.e - 11111111. Or simply, char value at maximum will be 255, any value beyond it won't matter. 255 => 11111111

Now, when you print the value at char pointer as integer(char value), it will be printed as signed int, i.e. -1

Edit:

I made a mistake about how 511 will be stored in memory. Please follow the answer by Abhishek yadav on this same page. Thanks, Abhishek!

When I mentioned max value for char is 255, I meant for unsigned char. By default, the compiler treats char as "signed char", ranging from -128 to 127. 11111111 as signed char is -1 integer value.

edited by
2 votes
2 votes

@Akash Mishra has almost answered this question but i think he interpret some memory facts little wrong..

First of all we have to understand int i=511 is stored in memory in little endian format in binary form.

511 can represent as 111111111 in binary. Now according to our system architecture integer size very 2 to 4 bytes as system meets to 64-bit or 32-bit system.

Let's consider integer size is 4 byte means 32 bits. In little endian format last binary bits (mean last eight 1's of 511 )  put the first memory location of 1-byte and left bits put in second memory location of Byte (e.g 00000001 of 511), we follow same as futher more.

11111111

00000001

00000000

00000000

   1000           1001        1002          1003            these are assumable addresses of memory locaton

         

ptr
       1000

Since char can hold only one Byte address in all machine that's why ptr hold the first memory reference of int i.

So according to simple logic while dereferencing the pointer ptr should print the value of stored memory location(1000) i.e 255(binary eight 1's). Now here logic is that gcc compiler Bydefault  treat plain char as signed char (range -128 to 127) which have lower range than 255 predicted output. That is only  the reason for output -1.

If you want to cross check then replace char to unsigned char(range 0 to 255). Now your output will be showed 255 as previous prediction. Here 255 is the maxium value that 1 byte can hold so there should be no second thought of more than 255 for one byte if values are greater than they push in other memory location of integer size as follow the little endian format .

No related questions found