Hi I’m new to this, so could be me being dense, but String.toCharArray seems to only copy length -1 characters to a char buffer or in other words it chops the last character. I’ll just post up the interesting bits of the code:
Obviously the readSerial() function is a dummy one, but it returns the correct length of the string (5) but when I read the char array readEquip, it returns “Hell” which is fairly apt .
Am I being a dummy? I’ve only had 2 cups of coffee today.
With a char array like your readEquip, you always need to “leave room” for the terminating zero character at the end of the string. That is just how C-style strings work.
As to copying using the String.toCharArray method, it takes a maximum length so the correct thing to plug in there is the length of the readEquip array - 1.
@bko, actually you could put it like this msg.toCharArray(readEquip, sizeof(readEquip)); since toCharArray() already makes sure to fit the zero-terminator in too.
It’s not the max string length but the buffer size you pass as len parameter.
Building on @ScruffR, If you want to return the length of the character portion of the C string (not the size of the buffer) you can try sort of like this:
char readEquip[20] = "";
Particle.variable("readEquip", readEquip);
//------------------------------------------------------------
int readSerial()
{
String msg = "Hello";
msg.toCharArray(readEquip, sizeof(readEquip));
int i = 0;
while(readEquip[i])
{
i++;
}
return i;
}
Hi All thanks for your comments and code suggestions which were very helpful. I had mis-read the docs and assumed the len was the length of the string to copy, not the max buff size.
Before I post up again I’ll have that extra coffee!