How to terminate char array?

I get data from one Arduino to an other (Stalker to Yun) via radio with the RFM69 lib GitHub - LowPowerLab/RFM69: RFM69 library for RFM69W, RFM69HW, RFM69CW, RFM69HCW (semtech SX1231, SX1231H)

The lib writes the incoming data in a for loop to serial

    for (byte i = 0; i < radio.DATALEN; i++) {
      Serial.print((char)radio.DATA[i]);
    } 
    
    Serial.print("   [RX_RSSI:");Serial.print(radio.RSSI);Serial.print("]");
    Serial.println();

I tried to fill a char variable in parallel of writing to serial via

    char outputSd[radio.DATALEN+1]; 
    
    for (byte i = 0; i < radio.DATALEN; i++) {
      Serial.print((char)radio.DATA[i]);
      outputSd[i] = (char)radio.DATA[i];
    }

Atfer checking the output on the SD I noticed some odd characters at the end, the serial monitor says

#[12][2] 2015/05/21 00:49:24, 25.4, 22.2, 36,  8.625   [RX_RSSI:-64]
outputSd: 2015/05/21 00:49:24, 25.4, 22.2, 36,  8.6259Bé

on the SD via a terminal and # less I get

2015/05/21 00:34:54, 25.5, 22.2, 36,  8.624BéAM
2015/05/21 00:35:04, 25.5, 22.2, 36,  8.625BéAM
2015/05/21 00:35:14, 25.5, 22.2, 35,  8.626BéAM

I think the array is not terminated correctly. But

    char outputSd[radio.DATALEN+1]; 
    outputSd[radio.DATALEN+1] = '\0';

or

     char outputSd[radio.DATALEN+1]; 
    outputSd[radio.DATALEN+1] = 0;

does not help.

My problem is

  • do I have to terminate the char array manually?
  • if so on which position should I terminate radio.DATALEN+1 or radio.DATALEN
  • do I have to use = '\0' or = '0'; or = 0; or = NULL ??
  • do I have to terminate the char array manually?

Yes.

  • if so on which position should I terminate radio.DATALEN+1 or radio.DATALEN

After each character.

    for (byte i = 0; i < radio.DATALEN; i++) {
      Serial.print((char)radio.DATA[i]);
      outputSd[i] = (char)radio.DATA[i];
      outputSd[i+1] = '\0'; // Add a NULL after each character
    }
  • do I have to use = '\0' or = '0'; or = 0; or = NULL ??

Either '\0' or 0. The '\0' format indicates that you know that you are adding a NULL to a char array. The actual value is 0, but using 0 makes people wonder if you really meant '0', while using '\0' makes it quite clear that you mean NULL/zero.

1 Like

Many thanks Paul! Thought I had to add the termination at the end after finishing the loop or after initializing the array. But a good idea and a ever valid way to add it always after adding a new character!

Thought I had to add the termination at the end after finishing the loop or after initializing the array.

You could do that, but the NULL goes after the last character, NOT at the end of the array.

    char outputSd[radio.DATALEN+1];
    outputSd[radio.DATALEN+1] = '\0';

This will surely be wrong, because the last element of the array is outputSd[DATALEN]