Newbie trying to understand the Arduino IDE language : values & variables

Hello, I'm new at coding with the Arduino IDE. It isn't about the hardware itself right now but about manipulating values and variables.

I don't know how to convert a stream of serial bytes to a string variable.

I have the following code:

int size;
while ((size = client.available()) > 0) {
uint8_t* msg = (uint8_t*)malloc(size);
size =, size);
Serial.write(msg, size);
//String chineseSurname = msg.toString(); // error: request for member 'toString' in 'msg', which is of non-class type 'uint8_t* {aka unsigned char*}'
//String chineseSurname = String(msg);
//String chineseSurname = String(msg,size);
String chineseSurname.concat(msg, size);

I'm trying to get the value in Serial.write (msg, size) into a string variable, but I don't know how to do it.

I've tried the options above (commented them out) but none of them work.

Thanks for reading.

try casting msg to a char?

for(int i=0; i<size; i++)
  Serial.print((char) msg[i]);

Thank you so much. That worked! And now I'm able to convert the char array to a String and do substring searches!

This is horrifyingly bad style; don't do assignment in the test of an if statement!

((size = client.available()) > 0)

Also, what happens if this code runs before the incoming message is completely received?

A c string (ie, char array - not a String) needs a null terminator on the end, otherwise your program doesn't know when the end of it is. Since you're no longer passing a length with serial.print(), you're in undefined behavior land. You'd need to give it an extra byte, and set that to 0, before casting it to a char array for Serial.print. It may work now, but changes elsewhere in the sketch can easily make it not work - you're relying on what happens to be located in memory after the end of that array just so happening to be 0. Not something you can depend on.

Take a look at the serial input basics thread - it's got some great examples of the Right Way to handle input on serial ports (and how to do it without String - the String class is best avoided because of it's dependence on dynamic memory allocation; this can cause problems in the memory-constrained environment of a microcontroller). You generally want to avoid malloc()/free() and anything that uses them (like String) to ensure that you don't have hard-to-debug issues caused by running out of memory or memory fragmentation.