【发布时间】:2012-02-14 10:32:07
【问题描述】:
我正面临着将数组中的单个项目转换为单个算术类型的奇怪行为。
这是一个简化的测试用例:
void test1()
{
unsigned char test[10] = {0};
unsigned long i=0xffffffff;
*((unsigned long *)(&test[3])) = i;
int it;
for ( it = 0 ; it < 10 ; it++ )
{
printf("%02x ", test[it]);
}
}
void test2()
{
unsigned char test[10] = {0};
unsigned char test2[10] = {0};
test[2]=0xFF;
test[3]=0xFF;
*((unsigned short *)(&test2[1])) = *((unsigned short *)(&test[2]));
int it;
for ( it = 0 ; it < 10 ; it++ )
{
printf("%02x ", test2[it]);
}
}
详细来说主要是这个表达式:
*((unsigned short *)(&test2[1]))
我在其他一些平台(主要是嵌入式平台,如 PIC24)上遇到访问冲突。
所以我的问题是:这符合 C 吗?我在 C 标准中找不到任何东西,但也许我只是个盲人。
您是否知道在没有这种强制转换的情况下执行此操作的任何替代方法(不意味着循环字节到字节的复制/展开等!)并且我不需要知道平台的当前字节顺序?
谢谢!
【问题讨论】:
标签: c pointers casting access-violation dereference