【问题标题】:How to convert a char pointer array into a int pointer array in C如何在C中将char指针数组转换为int指针数组
【发布时间】:2020-04-27 21:33:52
【问题描述】:

我有一个 8 字节的 char 指针,其中存储了 2 个整数。如何将它存储在 int 数组指针中,以便 int 数组的第一个整数在 array[0] 中,第二个整数在 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。

【问题讨论】:

  • 16 等于 0x10 并且 0x10000000 等于 268435456 可能对您有价值。类似的18 是十六进制的0x12,0x12000000 是基数为10 的301989888。
  • 你可以调试代码,看看write_buff的地址在内存中发生了什么。
  • 严格来说,int* intArray = (int*) wirte_buff; //puts char pointer to 是a strict aliasing violation 和未定义的行为。您不能安全地将char 数组引用为int,除非引用的内存实际上是int 变量。在这种情况下,它不是。像这种糟糕的代码往往会被很多本应该更了解的人教授,因为 x86 系统非常容忍未对齐的访问,并且通常会让你侥幸逃脱。
  • (续)But not always.

标签: c arrays endianness


【解决方案1】:

假设您知道strict aliasing rule violation,您的代码将在 big endian 架构中生成您期望的结果,其中组成整数的四个字节从最高有效字节开始存储:

------------------------------------------------------------------------------
| byte3 (bit 24:31) | byte2 (bit 16:23) | byte1 (bit 8:15) | byte0 (bit 0:7) |
------------------------------------------------------------------------------

但您显然是在 little endian 架构机器上运行代码:

------------------------------------------------------------------------------
| byte0 (bit 0:7) | byte1 (bit 8:15) | byte2 (bit 16:23) | byte3 (bit 24:31) |
------------------------------------------------------------------------------

因此,为了在 char 数组中替换整数,您需要:

  1. i 的字节 0,即 i &gt;&gt; (8 * 0),位于 wirte_buff 数组的索引 0 处
  2. i 的字节 1,即 i &gt;&gt; (8 * 1),位于 wirte_buff 数组的索引 1 处
  3. i 的字节 2,即 i &gt;&gt; (8 * 2),位于 wirte_buff 数组的索引 2 处
  4. i 的字节 3,即 i &gt;&gt; (8 * 3),位于 wirte_buff 数组的索引 3 处

这翻译成

wirte_buff[n] = (i >> 8*(n)) & 0xFF;

当然,j 也是如此:

wirte_buff[4+n] = (j >> 8*(n)) & 0xFF;

【讨论】:

    【解决方案2】:

    这段代码在很多方面都是错误的。

    • char * wirte_buff= (char*) malloc(8*sizeof(char*)); 分配了 8 个 char* 并且没有数据。您不会在任何地方分配这些指针,因此它们保持未初始化状态。
    • i &gt;&gt; ... 等对有符号类型执行按位运算,这总是错误的。如果该值为负数,您最终会得到实现定义的结果。
    • 1234563 /p>
    • 如果你也应该避免这种情况,你不能通过另一个类型用(int*) wirte_buff; 读回char ...intArray[0],因为这些类型不兼容。您可能会读取未对齐的数据。您还将违反严格的指针别名,请参阅What is the strict aliasing rule?

    发布的代码没有预期的行为,我怀疑你可以挽救它。您将不得不从头开始重新编写,尤其要避免所有可疑的转换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-12
      • 2023-01-08
      • 1970-01-01
      • 2021-01-26
      相关资源
      最近更新 更多