【发布时间】:2019-01-31 01:51:36
【问题描述】:
假设我们有这个:
int main()
{
int32_t* value = (uint32_t*)malloc(sizeof(uint32_t));
uint32_t array[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
*value = *(uint32_t*)((char*)array + 8);
printf("Value is: %d\n", *value);
return 0;
}
本例中的值为 3。 为什么会这样? 如果我们将一个 uint32_t 转换为 char,这是否意味着一个 char 在 uint32_t 中是 4 字节,因此
array[9] = {0, 4, !!8!!, 12, 16, 20, 24, 28, 32};
有人可以解释一下吗?
【问题讨论】:
-
int32_t* value = (uint32_t*)malloc(sizeof(uint32_t));为什么要这样投射? -
你为什么要写一些混淆代码,然后问它为什么这样做?
-
无法复制。我得到 3。
-
@ChristianGibbons 我不确定,但我认为 OP 也获得了 3...
-
嗯,这实际上是学校的任务,他们使用 malloc 分配空间,还有另一个任务询问问题是什么。好吧,任务中的代码不会释放内存,但这不是重点。是的,我也得到 3,但为什么是 3?