Consider the following small example code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *i;
char *c1, *c2;
i = malloc(4);
*i = 65535;
c1 = i;
c2 = (char *)i;
printf("%p %p %p\n", i, c1, c2);
printf("%d %d", *c1, *c2);
free(i);
return 0;
}
In the example, I allocate memory to store an integer, which is pointed by i
. Then, I store the value 65535 (1111 1111 1111 1111) in *i
. The next thing I do is make two char* pointers also point to the integer. I do it two times, but in two different ways: c1 = i;
and c2 = (char *)i;
. Finally, I print all pointers and all values in the screen. The three pointers are pointing to the same address, and the two values *c1
and *c2
are correct (-1).
However, the compiler generates a warning in this line: c1 = i;
. The warning is generated because I did not use the (char *)
cast to do the assignment.
What I would like to ask is why the compiler generates this warning, since I do not see any difference in using c1 = i
; or c2 = (char *)i;
. In both cases, the result is the same address with the same size in bytes. And this is valid for all casts, even if it is a (int *)
cast, (float *)
cast, (short *)
cast, etc. All of them generate the same value, but the compiler will only accept it without a warning if the cast being used is of the pointer's type.
I really would like to know why the compiler asks for that cast, even if the result is always the same.