2

I have the below program in C:

main() {
    int arr[5]={100,200,300};
    int *ptr1=arr;
    char *ptr2=(char *)arr;
    printf("%d\n",sizeof(int));
    printf("%d   %d",*(ptr1+2),*(ptr2+4));
    return 0; 
}

Its output is as follows:

4
300 -56

Please explain the last output. As per my understanding the last output should be 44 rather than -56.

4
  • 4
    Why do you think it should be 44? Commented Oct 2, 2014 at 11:32
  • 3
    It depends on endianness Commented Oct 2, 2014 at 11:34
  • Ok I had run it in compiler where int is 2 bytes. In that case it gives output as 44. Well it depends also on how many bytes an integer takes. Commented Oct 2, 2014 at 11:48
  • 1
    Yea, with two byte ints, that code picks out the first octet of 300, which is stored as 44, 1. Commented Oct 2, 2014 at 11:54

2 Answers 2

4

You are picking out the first octet of arr[1]. Your machine is little endian with 4 byte int and so the 4 octets that make up arr[1] are, written as decimal:

200, 0, 0, 0

So you are interpreting the octet 200 as a char. Your char is signed, and your machine uses two's complement.

The binary representation of 200 is

11001000

Since the most significant bit is set, this is a negative number when viewed as a signed value. So, to work out the magnitude of the negative value, we invert the bits, and add one.

00110111

is 55 in decimal. Hence the value output is -56.

Sign up to request clarification or add additional context in comments.

1 Comment

One could also say that, since values wrap around, and char is obviously interpreted as being in the range -128 - 127 (by this particular compiler), 200 is interpreted as the negative value 200-256 = -56.
2

In fact, you expected 44 what it would be if you had sizeof(int) = 2, because then *(ptr2 +4) would point to 300= 256 + 44 with a hex representation of 1002E and a last byte of 2E or 44 in decimal.

To get it independently of the size on an int, you should write :

printf("%d   %d",*(ptr1+2),*(ptr2+(2 + sizeof(int)));

But it will still depend on endianness, and give 0 on a big endian computer ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.