short question. I came upon this line of programming in someone's example code of Teensy Wire
Wire.write((byte *) &data, sizeof data);
arguments are (data sending, the size of the data). I don't understand what the (byte *) &data is for? I'm assuming its taking the address of the data and converting the data to bytes, but I don't know the syntax or why not just put
Wire.write(data, sizeof data);
/* Data is a */
struct with{
int id;
int data;
}
this code is for sending the structure across a wire to another device.
CodePudding user response:
Wire.write appears to take a pointer to byte as its first parameter, so simply passing data won't work because data is an object not a pointer. &data gives a pointer, but not of the expected type. (byte *) casts that pointer to one of the proper type.
CodePudding user response:
If the code is valid, I guess the class method write is declared like
size_t write(const byte* data, size_t size);
Thus, it expects a pointer to byte. Taking the address &data has the type data*, the pointer to with.
Wire.write(&data, sizeof data);
would raise the error
error: no matching function for call to 'write'
Wire.write(&data, sizeof data);
^~~~~
note: candidate function not viable: no known conversion from 'with *' to 'const byte *' for 1st argument
size_t write(const byte* data, size_t size);
because of the different sizes of pointees, byte is likely 8-bit type, wish with two int is more than 32-bit type. The pointer wish* should be forcedly type casted to byte*, but the safe type cast static_cast<byte*>(&data) from wish* to byte * is not allowed, and the author uses unsafe C-style type cast (T)v:
Wire.write((byte*)&data, sizeof data);
