cpost-incrementpostfix-operator

Int pointer cast into char pointer is not deferencing correctly


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


Solution

  • *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;