在铸件C,那么解引用指针 [英] casting then dereferencing pointers in C
问题描述
在与字符
在C缓冲器工作,有时它会是有用的,更有效的能够与 INT
一次-sized数据块。要做到这一点,我可以投我的char *
到为int *
,并使用该指针来代替。不过我并不完全相信,这工作我的思维方式确实。
When working with char
buffers in C, sometimes it would be useful and more efficient to able to work with int
-sized chunks of data at a time. To do this I can cast my char *
to an int *
and use that pointer instead. However I'm not entirely confident that this works the way I think it does.
例如,假设我有的char *数据
,确实 *(* int32_t)的数据= -1
总是覆盖字节数据[0]
,数据[1]
,数据[2]
和数据[3]
并没有其他字节?
For example, suppose I have char *data
, does *(int32_t *)data = -1
always overwrite the bytes data[0]
, data[1]
, data[2]
and data[3]
and no other bytes?
推荐答案
拓展我的评论。
这里有两个主要问题:
- 这违反了严格走样。
- 您可能打破对齐。
违反严格走样技术上的未定义行为即可。你被允许使用别名的char *
任何数据类型,而不是周围的其他方式。
Violating strict-aliasing is technically undefined behavior. You are allowed to alias any datatype with char*
, but not the other way around.
您可以解决此问题与 F [无糖]严格走样
的GCC。
You can get around the issue with f[no-]strict-aliasing
on GCC.
另一个问题是对齐。在字符
指针可能无法正确对齐。访问不对齐的数据可能会导致性能下降,甚至是硬件异常如果硬件不支持未对齐的访问。
The other issue is alignment. The char
pointer might not be properly aligned. Accessing misaligned data may lead to performance degradation or even a hardware exception if the hardware doesn't support misaligned access.
如果性能是不是一个问题,全防爆方式是的memcpy()
到 INT
数组缓冲区。
If performance isn't an issue, the full-proof way is to memcpy()
to an int
array buffer.
在这两个问题都解决了,你的例子:
Once these two issues are resolved, your example with:
*(int32_t *)data = -1
覆盖数据[0]
,数据[1]
,数据[2]
和数据[3]
应该按预期工作如果的sizeof(int32_t)== 4
。只是要注意字节顺序...
overwriting data[0]
, data[1]
, data[2]
, and data[3]
should work as expected if sizeof(int32_t) == 4
. Just pay attention to the endianness...
这篇关于在铸件C,那么解引用指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!