我不明白这个c ++术语

时间:2015-09-17 15:47:28

标签: c++

我已经看过一些源代码的最后一句。请解释一下这是什么。

unsigned int dataPos;
unsigned char header[54];
dataPos    = *(int*)&(header[0x0A]);

4 个答案:

答案 0 :(得分:3)

unsigned int dataPos; // dataPos is defined as unsigned integer
unsigned char header[54]; // header is an array of unsigned chars

最后一行有点乱,但是你可以分解它:

unsigned char *tmp1 = &header[0x0A]; // take the pointer to the tenth element
int *tmp2 = (int *)tmp1;             // convert it to a pointer to int
dataPos = *tmp2;                     // copy the integer tmp2 points to to dataPos

实际上,这个表达式不是100%安全的,因为原始数组header被定义为无符号字符数组,后来从位置10开始的字节作为整数访问。在大多数平台上,整数是对齐的,因此地址可以被4整除,而字符数组可以从任何地址开始。这意味着第十个元素可能不对齐。这可能会在某些平台上导致运行时错误。

答案 1 :(得分:2)

这是人们应该非常小心的事情。

它采用0x0A数组的第11个(header)元素的地址 (&(header[0x0A])等同于(header + 0x0A))并将char *const指针转换为int *指针,然后访问存储在该位置的(潜在)整数。

然后它会将int转换为unsigned int(这很好)。

所以基本上:“位置int内的char数组中有一个10(从0开始计算。)去那里捡起来。

据我所知,这只是定义的行为,如果该地址以前用于存储int,否则您可能会遇到一些未定义的行为问题,包括但不限于对齐问题。

答案 2 :(得分:1)

请您指明您不了解的那条线的哪个部分/运营商!句子由以下元素组成的任何方式:

  1. *:取消引用运算符
  2. (int *):cast to int
  3. &amp ;:地址 - 运营商
  4. header [0x0A]:存储在位置10的数组值
  5. 所以基本上它"阅读"由存储在头部数组的位置10,11,12和13中的字节形成的整数,并将其存储在变量dataPos中。

答案 3 :(得分:0)

也许我的评论会有所帮助:

unsigned int dataPos; // integer value
unsigned char header[54]; // character array (string)
dataPos    = *(int*)&(header[0x0A]);

// first 0x0a = 0xA = 10
// so header[0x0A] means get 10th element of array
// & in front of something means get address of
// so get address of (pointer to char) 10 element.
// now *(int *) is tricky (int *) would convert address you of 
//       header[10] and convert it to int pointer.
//
// finaly * in front of (int *) would say get the value stored in adress pointed to