我有一个8字节的char指针,里面存储了2个整数。我如何将它存储在int数组指针中,使int数组中的第1个整数是在 array[0] 而第2个整数是在 array[1].
我做的代码到目前为止。
char * wirte_buff= (char*) malloc(8*sizeof(char*));
int i, j;
i = 16;
j = 18;
/*separates integer i and integer j into 4-bytes each*/
for(n=0; n<=3; n++){
wirte_buff[n] = (i >> 8*(3-n)) & 0xFF;
wirte_buff[4+n] = (j >> 8*(3-n)) & 0xFF;
}
int* intArray = (int*) wirte_buff; //puts char pointer to
printf("intArray[0] value is %d \n", intArray[0]);
printf("intArray[1] value is %d \n", intArray[1]);
当我这样做的时候,预期的结果是16和18, 但我意外地得到了268435456和301989888.
1
投票
假设你知道 严禁别名你的代码会产生你所期望的结果。橡皮筋 架构,其中组成一个整数的四个字节从最重要的字节开始存储。
------------------------------------------------------------------------------
| byte3 (bit 24:31) | byte2 (bit 16:23) | byte1 (bit 8:15) | byte0 (bit 0:7) |
------------------------------------------------------------------------------
但显然你的代码是在一个... 苣荬菜 架构机。
------------------------------------------------------------------------------
| byte0 (bit 0:7) | byte1 (bit 8:15) | byte2 (bit 16:23) | byte3 (bit 24:31) |
------------------------------------------------------------------------------
所以,为了在char数组中替换你的整数,你需要这样做。 你需要:
i即
i >> (8 * 0),是在索引0的
wirte_buff 阵列 字节1的
i即
i >> (8 * 1)的索引1,在
wirte_buff 阵列 字节2的
i即
i >> (8 * 2),是在索引2的
wirte_buff 阵列 字节3的
i即
i >> (8 * 3)的第3位。
wirte_buff 阵列
这可以翻译为
wirte_buff[n] = (i >> 8*(n)) & 0xFF;
当然也包括 j:
wirte_buff[4+n] = (j >> 8*(n)) & 0xFF;
0
投票
这段代码在很多方面都是错误的。
char * wirte_buff= (char*) malloc(8*sizeof(char*)); 分配8
char* 而没有数据。你没有将这些指针分配到任何地方,所以它们保持未初始化。
i >> ... etc 在有符号类型上执行位运算,这总是错误的。如果值是负的,你最终会得到实现定义的结果。
你应该将 int 值为 char那么 char 具有实现定义的签名性,所以你不知道你最终是否会得到一个负值或者可能是一个溢出的underflow。
如果你也要避免这种情况,你就不能读取一个叫做 char 回过头来 (int*) wirte_buff; ... intArray[0] 因为这些类型不兼容。你可能会读取错误对齐的数据。你还会违反严格的指针别名,参见 严格的别名规则是什么?
发布的代码没有预期的行为,我怀疑你能否挽救它。你必须从头开始重新编写,尤其要避免所有的蹊跷转换。