Hello,
1 unsigned char ar[] = "AB";
2 unsigned int i = 0;
3 i = *(unsigned int *)ar;
How does it convert to unsigned int from unsigned char()? After
executing this three line I am getting 16961! How does this value
actually derived?
Thanks
JK
Here's another view of what is happening here:
The name ar denotes an array of unsigned char. In some places, ar
will 'decay' into a pointer to the first element of the array. Here
the type of the pointer would be 'unsigned char *'.
When you cast that pointer to another type, the compiler doesn't
convert it. It is YOU who say "the pointer is not a pointer to an
unsigned char, it is really a pointer to an unsigned int. Trust me,
I know what I am doing!". And the compiler is forced to trust you,
because that's the contract it works under.
If you then dereference the pointer, and it actually DOES point to
an unsigned int, you get the value of the int.
If you dereference the pointer, and it actually does NOT point to
an unsigned int, you have broken the contract with the compiler. It
is the free do do anything it feels like, perhaps show the value
16961. Or crash, or format your harddisk.
Just don't lie to the compiler.
Bo Persson