简体   繁体   English

Arduino C ++ char数组为空,元素被填充

[英]Arduino C++ char array is empty, elements are filled

I'am trying to print a char array to serial. 我正在尝试将char数组打印到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那么输出看起来像

abcdefg
-------

END

So why can the elements be printed, while the whole array can't? 那么为什么要打印元素,而整个数组不能?

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. 它可能包含null,因此它会在那里终止你的字符串。 To fix it, use post-increment: 要修复它,请使用后增量:

buffer[bufferpointer++]=data;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM