#include "stdio.h"
/* array to store data receeived from CAN Bus */
unsigned char a[8] = {0xCD, 0xEF, 0x12, 0x34, 0x50, 0x00, 0x00, 0x00};
typedef struct {
unsigned int a:12;
unsigned int b:12;
unsigned int c:12;
unsigned int unused:28;
}test;
test *tptr;
int main(void)
{
tptr = (test*)((void*)&a); // is this line braking any aliasing rule
if(tptr->a == 0xCDE)
{
printf("\n data received ok");
}
return 0;
}
我最近了解到由于C中的指针别名问题。我想知道上面的代码是否违反了任何规则。它会导致问题吗?可以指向结构别名unsigned char数组的指针吗?
我知道位域的顺序是依赖于机器和实现的。然而,我的问题是关于指针别名规则,我想更清楚地理解它
这不是测验网站。你为什么认为它不? – Olaf
'#include“stdio.h”'是不寻常的。你为什么不使用'#include'? –
melpomene
我不知道别名,但我很确定'tptr = ...'行有未定义的行为。首先,'B x; (A *)(void *)&x'不能保证做任何明智的事情(你只能保证能够从'void *'转换回原始类型'B *')。其次,即使它工作,结构可能有对齐要求。 – melpomene