简体   繁体   中英

Pointers and casting in C/C++

I am very confused with this kind of casting. Can someone explain what exactly it is happening in this sentence?

x = *(char*)&n;

That is the complete code, and it is used to know if a machine is little endian or big endian.

 int n = 0x1234567;
 char x;
 x = *(char*)&n;

&n takes the address of n , but crucially, it's the lowest-addressed byte of n . (char *) tells the compiler to treat that address as a pointer to a char , ie a pointer to a single byte. * dereferences that, ie it obtains the byte value stored at that address.

So the overall effect is that x is set to the value stored in the lowest-addressed byte of n .

&n takes the address of n , which is the address of an integer.

(char*)(&n) reinterprets this information as the address of a char .

*(char*)(&n) dereferences this address, that is, it is the value of the char that lives at that address. In other words, it's the value of the first byte of the representation of the integer n .

Now you can check whether that's 0x01 or 0x67 to determine which way round your integer is stored.

As a side note: It is always permitted to reinterpret any valid address as the address of a char and inspect it, both in C and in C++. This is necessary whenever you want to perform I/O, since you can only input/output dumb byte streams, which you obtain in this fashion (that is, you can treat any T x; as a char[sizeof(T)] and access it via (char*)&x ).

To help you visualize why this code can be used to detect the 'endiannes' of the environment.. In a big endian environment that uses 32bit ints the number will be stored in memory in this byte order

01 23 45 67

In a little endian environment it will be this order

67 45 23 01

If you forcibly cast an int pointer to an initialized int to a char pointer, the char pointer will be deferenced to the first byte of the int as it is stored in memory.

In a big endian environment this will deference to 01 and in a little endian environment it will be 67 .

If ints aren't 32 bits you'll get different values altogether.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM