Reputation: 4073
I'am trying to print a char array to serial. The array itself is filled with chars, but as soon as I'am printing the whole array - and not just elements of it - the string printed is empty.
#define MAX_PAYLOAD_SIZE 80
class CmdBuffer {
...
private:
char buffer[MAX_PAYLOAD_SIZE+1];
int bufferpointer;
...
};
//In cpp File
String CmdBuffer::readCommand(char data) {
buffer[++bufferpointer]=data;
if(data != CMD_EOF) {
return NULL;
}
buffer[++bufferpointer]='\0';
...
for(int i=0; i<bufferpointer; i++) {
Serial.print(buffer[i]);
}
Serial.println("\n-------");
Serial.println(buffer);
Serial.println("END");
...
}
If the input chars are abcdefg
then the output looks like
abcdefg
-------
END
So why can the elements be printed, while the whole array can't?
Upvotes: 1
Views: 1525
Reputation: 62093
I suspect it's because you are not assigning the first character:
buffer[++bufferpointer]=data;
Because of the pre-increment, you're missing the first character. It probably contains a null, so it terminates your string right there. To fix it, use post-increment:
buffer[bufferpointer++]=data;
Upvotes: 4