toCharArray not copying all characters - loses last char

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:

char readEquip[20] = "";

  Particle.variable("readEquip", readEquip);

//------------------------------------------------------------
int readSerial()
{
    String msg = "Hello";
    msg.toCharArray(readEquip, msg.length());
    return msg.length();
}

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 :smile: .

Am I being a dummy? I’ve only had 2 cups of coffee today.

Cheers

Steve

The docs for String.toCharArray() state that the len parameter represents the size of the target buffer and not the string length.

You must know that a C string has to be terminated with a zero character ('\0') which needs to fit into the buffer too.

2 Likes

Hi @picitup

I see that yet again @ScruffR beat me to it!

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.

2 Likes

@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.

1 Like

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;
}

Or just use strlen(readEquip) for the size.

2 Likes

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!

Kind Regards

Steve

3 Likes