2,481 views
1 votes
1 votes
#include<stdio.h>
main()
{
int i=511;
char *ptr=(char *)&i;
printf("%d",*ptr);
}
explain...how output came -1????

1 Answer

1 votes
1 votes

Since the question does not mention exactly where you got stuck, I would quickly discuss three components that are required for this question.

Little-Endianness is considered Default

Endianness is essentially styles of storing multi-bytes in memory. There are two of them, one is Little-Endian and the other one is Big-Endian. Majorly because of the popularity of Little-Endianness among hardware designers, it is considered default while solving such questions. Read this article to know more about them.

With this in mind, contents of the variables used in the program and a glimpse of contents of memory will be something like this.

Range of char (signed) is $-128$ to $+127$

Char data type are usually 8 bit long, where MSB is reserved for the sign. Now, no matter how much odd it may sound to have signed and unsigned character, but they do exist in c language (ref). One of many reasons for this is that there are only $127$ ASCII characters, which can be uniquely represented with just 7-bits, thereby leaving us with one extra bit being the reason for such questions. To bring this bit into good use, not so popular Extended ASCII was later introduced with unsigned characters. So all those negative numbers in char data type from $-128$ to $-1$ are essentially worthless. However, they are still represented just like other negative integers, i.e., in 2's complement.

Integer equivalent of $(11111111)_2$ typecasted as char is $-1$

$p$ is a char pointer, and thus the contents of the location it is pointing to will be considered char and thereby only one byte will be fetched from memory. MSB of the byte just fetched from memory is $1$. Which means the number is negative (when considered as a character[1]) and therefore we have to take 2's complement of $(11111111)_2$ to obtain true magnitude of the equivalent integer. And since, the number was negative, to obtain integer equivalent we put a negative sign before the true magnitude.

Roughly, this is what the machine would have done after encountering machine language equivalent of the statement "printf("%d",*ptr);"


[1] Had it been an integer, the statement would have fetched two bytes from memory. Since the location was pointed by a char pointer, the memory content was considered a character and the second byte was not fetched.

Related questions

0 votes
0 votes
0 answers
1
himgta asked Feb 19, 2019
363 views
https://www.sanfoundry.com/c-program-checks-strings-anagrams/what is the meaning of line number 32?
1 votes
1 votes
1 answer
2
Satbir asked Jan 16, 2019
662 views
#define lol(a) a+a*aint main(void) { int a=3;printf("%d",lol(a+2)); return 0;}what is the output ?
0 votes
0 votes
0 answers
3
Shubham Aggarwal asked Sep 1, 2018
372 views
Please explain i am not able to understand it.
0 votes
0 votes
1 answer
4