Strcat (with MRE)

char gLog [5];
char gCode[3];

byte idx;

void setup() {
  Serial.begin(19200);
  gCode = "E";
}

void loop() {
  for(idx = 0; idx < 3; idx ++)
  {
    strcat(gLog, gCode);
    Serial.println(gLog);
    delay(2000);
  }

  gLog = "";  // blank gLog, start over
}

Desired / Anticipated Result:

E
EE
EEE
E  // and so on ...

Verify/Compile --
incompatible types in assignment of 'const char [2]' to 'char [3]'

I don't get it.

C/C++ does not allow copying one array to another using "=". Instead,

strcpy(gCode,"E");

To use strcat, assuming gCode is initialized to zero,

strcat(gCode,"E");
Serial.println(gCode);  //should print E
strcat(gCode,"E");
Serial.println(gCode); //should print EE
strcpy(gCode, "E");

@jremington and @sterretje
Thank You.

char gLog [5];
char gCode[3];

byte idx;

void setup() {
  Serial.begin(19200);
  strcpy (gCode, "E");
}

void loop() {
  for(idx = 0; idx < 3; idx ++)
  {
    strcat(gLog, gCode);
    Serial.println(gLog);
    delay(2000);
  }

  strcpy (gLog, "");  // blank gLog 
}

I thought strNcat was advised in Arduino c++ code over strcat... (and strncpy ... et c.)

It is indeed. The OP and other readers are hereby reminded that this construction can safely contain a C-string consisting of only two ASCII characters, plus the terminating zero.

char gCode[3];

Although not part of the C standard library, the 'l' versions (strlcat() and strlcpy()) are considered safer as you always pass the full size of the destination buffer.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.