Int pointer cast into char pointer is not deferencing correctly

53 views Asked by At

I am trying to see how endianness applies on my system. Using Python sys module, I found that its little endian, which means that least significant bytes are at lower memory addresses. So, I wanted to use C to play around this. Here is the code

int main(int argc, char *argv[])
{
    int x = 0x2e1f34;
    char *ptr = (char *) &x;
    char y = *ptr;

    printf("y = %#x\n", y);
    y = *ptr++;

    printf("y = %#x\n", y);
    y = *ptr++;

    printf("y = %#x\n", y);

    return 0;
}

Following is the output

y = 0x34
y = 0x34
y = 0x1f

First value is right. But second value should have been 0x1f as ptr has increased to the next byte address. So, using operator precedence table, pointer is increased first and then its deferenced. So, second value should be 0x1f since there is little endianness. So, what is the cause of this behavior ?

Thanks

2

There are 2 answers

3
KamilCuk On BEST ANSWER

*ptr++ gets the value and after that increments the pointer. Your code can be rewritten as:

char y = *ptr;
printf("y = %#x\n", y);
y = *ptr;
ptr++;
printf("y = %#x\n", y);

Now it should be more visible that first two y have the same value.

If you want to increment first, you could do *(++ptr) or just ptr++; y = *ptr;

0
Vlad from Moscow On

From the C Standard (6.5.2.4 Postfix increment and decrement operators)

2 The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it).

Compare the description of the postfix increment operator with the description of the unary increment operator (the C Standard, 6.5.3.1 Prefix increment and decrement operators)

2 The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation. The expression ++E is equivalent to (E+=1).

So in both these lines

char y = *ptr;

//...

y = *ptr++;

the value of the variable y will be the same.

Instead you could write for example using unary increment operator

char y = *ptr;

//...

y = *++ptr;

Or alternatively you could write

char y = *ptr++;

//...

y = *ptr++;

Using already the postfix increment operator in the initializing expression in the declaration of the variable y.