Looking at the code:
#include <stdio.h>
#include <stdint.h>
int main() {
char foo[512]={};
printf("%d", *((uint32_t*)foo));
return 0;
}
I'm having hard time understanding what *((uint32_t*)foo)) does, Using different values in array I'm getting all kinds of return values.
What exactly does it point to and so what's the return value?
In this expression,
foois type-casted to auint32_tpointer and then dereferenced.Dereferencing a cast of a variable from one type of pointer to a different type is usually in violation of the strict aliasing rule¹, and
does exactly that. So the expression invokes undefined behaviour.
Furthermore,
foomight not be properly aligned:From C11:
With 6.3.2.3p7 saying
Unaligned data is data at an address (pointer value) that is not evenly divisible by its alignment (which is usually its size).
NB that empty initializer lists are not valid till C23, and just because
int32_thappens to beinton your compiler/platform doesn't mean that it might not belongon another.%din not the correct format specifier for anint32_t. If you don't want to use the specific macros for fixed-width integer types, another approach is to cast tointmax_t/uintmax_tand use%jdand%jurespectively.Footnote:
1
See: What is the strict aliasing rule?