从char数组的末尾读取4个字节

use*_*112 1 c++ arrays binary byte reinterpret-cast

如果我有一个char*数组:

char* c = getBytesFromSomewhere();
Run Code Online (Sandbox Code Playgroud)

我想将最后4个字节读取到uint然后读取前4个字节等.我试过这个:

char* end = &c[size-5];
Run Code Online (Sandbox Code Playgroud)

获取指向数组中最后4个字节的指针,然后:

unsigned int n = *(reinterpret_cast<int *>(end));
Run Code Online (Sandbox Code Playgroud)

但它似乎没有起作用......我做错了什么?

Som*_*ude 6

让我们说返回的数组大小为8,它在内存中看起来像这样:

+---+
| c |
+---+
  |
  v
  +---+---+---+---+---+---+---+---+
  | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
  +---+---+---+---+---+---+---+---+

(里面的数字是索引.)

现在,如果你创建一个新变量e指向c + size它,它将指向超出数据末尾的变量:

+---+                           +---+
| c |                           | e |
+---+                           +---+
  |                               |
  v                               v
  +---+---+---+---+---+---+---+---+
  | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
  +---+---+---+---+---+---+---+---+

如果你1从中减去e它现在指向索引7:

+---+                       +---+
| c |                       | e |
+---+                       +---+
  |                           |
  v                           v
  +---+---+---+---+---+---+---+---+
  | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
  +---+---+---+---+---+---+---+---+

如果你减去两个(总计)e将指向索引6,减去3e指向索引5和减法4,指向的索引将是4.如果你减去5指针e会指向索引3:

+---+       +---+
| c |       | e |
+---+       +---+
  |           |
  v           v
  +---+---+---+---+---+---+---+---+
  | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
  +---+---+---+---+---+---+---+---+

这不是最后的四个字节,即距离结尾的五个字节.

所以你应该这样做

char* end = c + size - 4;  /* Subtract by 4 and not 5 */
Run Code Online (Sandbox Code Playgroud)

如果数据来自其他系统,例如通过Internet,您还应该注意字节顺序.