Let's take this example code:
#include <stdio.h>
int main(void){
int x = 1;
if(*(char *)&x == 1) printf("little-endian\n");
else printf("big-endian\n");
return 0;
}
I have seen this (or similar one) instruction *(char *)&x
multiple times and now i want to completely understand what does it mean!
I think it means:
1) take the address of the int variables
2) then cast it to a char pointer
3) then compare the first element of the "new char pointer" with the number 1.
Am i right?
We saw that pointer values may be assigned to pointers of same type. However, pointers may be type cast from one type to another type. In the following code lines, A is an int type variable, D is variable of type double, and ch is a variable of type char.
Type casting is the process in which the compiler automatically converts one data type in a program to another one. Type conversion is another name for type casting. For instance, if a programmer wants to store a long variable value into some simple integer in a program, then they can type cast this long into the int.
You're about right, but a better listing would be:
x
char
at &x
1
Note that this is rather edgy code, the read value will depend on the machine's byte endianness.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With