这段代码发生了什么?的reinterpret_cast <INT*>(BUF)

0 c++

在我看来,缓冲区正在被修改.它是否将6个整数和5个浮点数放入缓冲区?他们将大小设置为44而不是1024*sizeof(char)也很奇怪.也许整个缓冲区传递给write()但write()只将前44个字节写入客户端.

你能逐行解释一下吗?我没有使用c ++的经验.

char buf[1024];
int* pInt = reinterpret_cast<int*>(buf);
*pInt = 5;
*(pInt+1) = 2;
*(pInt+2) = 3;  
*(pInt+3) = 4;
*(pInt+4) = 5;
*(pInt+5) = 6;

float* pFloat = reinterpret_cast<float*>(pInt+6);
*pFloat = 111;
*(pFloat+1) = 222;
*(pFloat+2) = 333;
*(pFloat+3) = 444;
*(pFloat+4) = 555;

int n;
int size = (1+2*5)*4;
n = write(buf, size);
Run Code Online (Sandbox Code Playgroud)

R S*_*ahu 6

它是否将6个整数和5个浮点数放入缓冲区?

是.

它们设置尺寸11而不是它也很奇怪1024*sizeof(char)

他们不想写整个缓冲区.你想只写出写入缓冲区的ints和floats.

FWIW,这是一个写得不好的代码.它假设sizeof(int)并且sizeof(float)都等于4.更便携的方法将使用:

int size = 6*sizeof(int) + 5*sizeof(float);
Run Code Online (Sandbox Code Playgroud)

警告

即使发布的代码可能在某些情况下,也许是大多数情况下都可以使用

int* pInt = reinterpret_cast<int*>(buf);
*pInt = 5;
Run Code Online (Sandbox Code Playgroud)

是标准的未定义行为的原因.它违反了严格的别名规则.int在那个位置没有开始.

你用过:

int array[5] = {};
char* cp = reinterpret_cast<char*>(array);

// ...

int* iptr = reinterpret_cast<int*>(cp);
*iptr = 10;
Run Code Online (Sandbox Code Playgroud)

没有问题,因为cp指向一个int开始的地方.

对于您的用例,最好使用:

char buf[1024];
int intArray[] = {5, 2, 3, 4, 5, 6};
std::memcpy(buff, intArray, sizeof(intArray));

float floatArray = {111, 222, 333, 444, 555};
std::memcpy(buff+sizeof(intArray), floatArray, sizeof(floatArray));

int n;
int size = sizeof(intArray) + sizeof(floatArray);
n = write(buf, size);
Run Code Online (Sandbox Code Playgroud)

进一步阅读:

  1. reinterpret_cast创建一个简单的默认构造对象
  2. 工会和打字