我真的很困惑。
uint8_t hash[20];
uint32_t u;
// Setting hash to some value here...
u = *(uint32_t*) hash;此*(uint32_t*) hash会导致警告:
Dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]。
我认为这是类型转换的错误,但我不确定,因为我不清楚*(type*) var的类型转换方式实际上是如何工作的。它似乎指向一个里面也有星号的物体。我很困惑,这就是迫使我问这个问题的原因。我特别想知道type*和*(type*)有什么不同。这可能对摆脱这个警告有很大的帮助。提前谢谢。
发布于 2014-11-03 20:04:22
不允许您通过不兼容的指针解释对象,因为您这样做:
*(uint32_t*) hash;这样做将导致对齐、字节顺序和违反严格别名的问题,这将导致未定义的行为。
发生的情况是,您将数组哈希的前四个字节解释为一个无符号32位整数。
uint32_t* p = ( uint32_t* )hash ; //cast must be there, pointer p is not valid
uint32_t u = *p ; //dereference the pointer, this is undefined behaviour如果字节数组编码的是低端32位无符号整数,这是一种可移植的、独立于字节顺序的提取方法:
#include <stdint.h>
#include <limits.h>
uint8_t h[] = { 3 , 2 , 1 , 0 } ; //1*3 + 256*2 + 65536*1 + 16777216 * 0
uint32_t a = 0 ;
for( size_t i = 0 ; i < sizeof( a ) ; i++ )
{
a = a | ( h[i] << ( CHAR_BIT*i ) ) ;
}
printf("%u" , a ) ; //66051https://stackoverflow.com/questions/26713851
复制相似问题