For example, I cast a pointer to an int
to a pointer to char
:
int originalVar = 1;
char *arr = (char *)&originalVar;
Then I cast it back (maybe I pass arr
to another function):
int *pOriginal = (int *)arr;
Does it break the rules? Or any undefined behaviors here?
--
Actually my doubts are about understanding the "effective type" in C standard
Does the object pointed by arr
always regard int
as its effective type?
(Even if arr
is passed to another function?)
That works and is well defined because the alignment of the original pointer will match the int.
Only issue casing a char* to an int* can be alignment requirements. Certain architectures require an int to be aligned on a 4-byte boundary (ie. the last two binary digits of the pointer are 0). A char* generally does not have that limitation.
However, since it started as an int*, and int* -> char* is never an issue, this will not cause any issue.