The below program tests for Little/Big endian on intel processor. Actually little endian is correct output. First I am casting int
to char*
and accessing its value without initialization to int *
.I am not understanding second part of output. Here int
pointer is casted to char *
. So why is not int
pointer not changed its alignment to char *
?
00000000 00000000 00000011 01111111 = 895
0 0 3 127
int main() {
int num = 895;
if(*(char *)&num == 127)
{
printf("\nLittle-Endian\n");
}
else
{
printf("Big-Endian\n");
}
int *p = (char *)&num ;
if(*p == 127)
{
printf("\nLittle-Endian\n");
}
else
{
printf("Big-Endian\n");
}
printf("%d\n",*p);
}
o/p
Little-Endian
Big-Endian
895
No, it changes the default interpretation of what the pointer points to. When you read from an int pointer in an expression *myIntPtr you get back the content of the location interpreted as a multi-byte value of type int .
When casting character pointer to integer pointer, integer pointer holds some weird value, no where reasonably related to char or char ascii code. But while printing casted variable with '%c', it prints correct char value. Printing with '%d' gives some unknown numbers.
Typecasting is a way to make a variable of one type, such as an int, act like another type, such as a char, for one single operation. To typecast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable.
void* to char** You can't. You need reinterpret_cast. You have a 'pointer to anything' and have decided to treat it as a 'pointer to a char*'. That is 'reinterpreting' the type of the memory without applying any conversions.
The first half of your program using this comparison:
if(*(char *)&num == 127)
looks fine.
The second half of your program contains this assignment:
int *p = (char *)&num ;
Which isn't valid code. You can't convert pointer types without an explicit cast. In this case, your compiler might be letting you get away with it, but strictly speaking, it's incorrect. This line should read:
int *p = (int *)(char *)#
or simply this equivalent statement:
int *p = #
From this example, I'm sure you can see why your second test doesn't work the way you'd like it to - you're still operating on the whole int
, not on the single byte you were interested in. If you made p
a char *
, it would work the way you expected:
char *p = (char *)#
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