0
 # include <stdio.h>
 int main()
 {
    char p[]={0x01,0x02,0x03,0x04};
    int *q = p;
    printf("%x",*q);
    return 0;

  }

When I run the above code, the answer is 4030201. Why?

2
  • "Why?" Because you got unlucky. Had the code printed 'UB detected. Please ask on SO why' you had got lucky! Commented Oct 6, 2019 at 13:58
  • 1
    int *q = p; is illegal in C. Your compiler told you about it. The rest is just experiments with undefined code. Commented Oct 6, 2019 at 14:01

1 Answer 1

1

It is because you compile and run your code on little-endian architecture machine (x86 for example)

At first you put 4 bytes in memory in order: 01 02 03 04. Than convert pointer to this array to pointer to int. On little-endian machine memory block 01 02 03 04 represents integer value 0x04030201 which is printed on next step.

See https://en.m.wikipedia.org/wiki/Endianness for more information

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

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.