代码:
unsigned char array_add[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
...
if ((*((uint32_t*)array_add)!=0)||(*((uint32_t*)array_add+1)!=0))
{
...
}
我想检查数组是否全为零。所以很自然地我想到了将数组的地址(也恰好是第一个成员的地址)转换为 unsigned int 32 类型,所以我只需要这样做两次,因为它是 64 位,8 字节大批。问题是,它已成功编译,但程序每次都会在此处崩溃。
我正在 8 位微 Controller cortex-M0 上运行我的程序。
我哪里错了?
最佳答案
理论上这可行,但实际上您没有考虑到一件事:对齐的内存访问。
如果 uint32_t
需要对齐内存访问(例如 4 字节),则将具有 1 字节对齐要求的 unsigned char
数组转换为 uint32_t *
生成指向未对齐的 uint32_t
数组的指针。
根据 documentation :
There is no support for unaligned accesses on the Cortex-M0 processor. Any attempt to perform an unaligned memory access operation results in a HardFault exception.
在实践中,这只是在某些情况下调用未定义行为的危险且脆弱的代码,正如 Olaf 所指出的并更好地解释了 here .
关于我可以这样投指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41156024/