Concatenate/append using <string.h>

Hello,

I am doing preparations for my new project. This involves some basic C knowledge.....

I have the following test code:

#include <string.h>
#include <stdlib.h>

//constants
const byte IputMaxLength = 30 + 1 + 1 + 1;//30 plus header plus footer plus terminating zero

const char Header = '~';
const char Footer = '#';

const char BtnU[] = "ButtonUp";
const char BtnD[] = "ButtonDown";
const char BtnL[] = "ButtonLefr";
const char BtnR[] = "ButtonRight";

char StringIn[IputMaxLength] = {
  '\0'};

int ledPin = 13;     // LED connected to digital pin 13

void setup(){
  pinMode(ledPin, OUTPUT);      // sets the digital pin as output
  Serial.begin(9600);
}

void loop(){  
  SerialRead();
}

void SerialRead(){
  // See if there's incoming serial data:
  if(Serial.available() > 0) {
    getIncomingChars();
  }
  Serial.println(StringIn);
}

void getIncomingChars() {
  // read the incoming data as a char:
  char CharIn = Serial.read();
  if ((strlen(StringIn)) < IputMaxLength) {
    strcat(StringIn, CharIn)
  }
}

I am getting this error message:

In function 'void getIncomingChars()':
error: invalid conversion from 'char' to 'const char*'

What am I doing wrong?

Thanks in advance!

There are two problems in your code. One problem is minor and easily fixed. The other problem is very serious.

First the minor problem...

strcat expects both parameters to be strings (arrays of characters terminated by a null). You are passing a char for the second parameter. Something like this will get you past the problem...

  char CharIn[2];
  CharIn[0] = Serial.read();
  CharIn[1] = 0;
  ...
    strcat(StringIn, CharIn);  // Note: you forgot the semicolon

The second (serious) problem is this line of code...

  if ((strlen(StringIn)) < IputMaxLength) {

You are not leaving space for the null terminator. I'll use an example to illustrate the problem...

Assume IputMaxLength = 4 and StringIn already has the letters 'a' and 'b' stored. This will be the memory contents...

[a] [0] [0]
The character 'c' arrives. strlen(StringIn) = 2 which is less than IputMaxLength so the strcat is executed leaving this...
** [a]**
```c
** [0]

No problem.  The character 'd' arrives.  strlen(StringIn) = 3 which is less than IputMaxLength so the strcat is executed leaving this...

[a] [b] [c] [d] [0]

Oops!  strcat wrote a null-terminator past the end of StringIn corrupting whatever is next in memory.
__
```**__