Does it put 6 integers and then 5 floats into the buffer?
Yes.
It's also strange that they set size to 11
instead of 1024*sizeof(char)
They don't want to write the entire buffer. Thy want to write just the int
s and float
s that were written to the buffer.
FWIW, that is poorly written code. It assumes that sizeof(int)
and sizeof(float)
are both equal to 4. A more portable method would use:
int size = 6*sizeof(int) + 5*sizeof(float);
Caution
Even though the posted code might work under some, perhaps most, circumstances, use of
int* pInt = reinterpret_cast<int*>(buf);
*pInt = 5;
is cause for undefined behavior by the standard. It violates the strict aliasing rule. There wasn't an int
to begin with at that location.
Had you used:
int array[5] = {};
char* cp = reinterpret_cast<char*>(array);
// ...
int* iptr = reinterpret_cast<int*>(cp);
*iptr = 10;
there would be no problem since cp
points to a place where an int
was there to begin with.
For your use case, it will be better to use:
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);
Further reading:
- reinterpret_cast creating a trivially default-constructible object
- Unions and type-punning