In the below snippet, I define foo
which is large enough to hold a 32-bit integer. However, when I try to store a 32-bit integer in foo
, it does not fit.
int8_t * foo = malloc(sizeof(int32_t));
int32_t value = 300;
foo[0] = value;
printf("%i ", foo[0]); // 44
Is there some way to use up more elements to store the value instead of truncating it?
foo[0]
has type int8_t
, so it is only big enough for 1 byte.
Although adjacent bytes ( foo[1], foo[2], foo[3]
) are available, the compiler doesn't know you intend to copy all 4 bytes when working with just foo[0]
.
Instead:
*((int32_t*)foo) = 300;
Which says, "Pretend that foo is the start of a 4-byte integer, then assign it the value 300" .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.