0

I have

char c;

where

int bt_available = Serial2.available();
if (bt_available) {
  c = Serial2.read();
}

and later in the code I try to

strcat(some_char_array, c);

and it gives me this error

initializing argument 2 of 'char* strcat(char*, const char*)' [-fpermissive]
error: invalid conversion from 'char' to 'const char*' [-fpermissive]

My best guess why the error appears would be that strcat can only accept strings and char arrays, but not single characters, so a solution I can think of would be to create a char array like char test[1] where test[1] = '\0' and then test[0] = c but I'm not sure if that's the best way to go about the problem and if that's a solution. Does 'const char*' mean 'char[]'?

P.S I read Majenko's blog thingy and I'm turning all Strings to char arrays and it's a bit of suffering :P

1 Answer 1

1

A char is a single character. A char * and a char[] are both arrays of characters (more correctly char * is a pointer to an array of characters).

strcat expects two arrays or pointers to arrays of characters. If you want to add a single character you can either fool the compiler into thinking that the character is an array of characters of size 1 (but it lacks the required NULL termination) or manually manipulate the target array.

For the former you could use strncat and casting:

strcat(some_char_array, &c, 1);

That gives you a pointer to the character, which is as far as the compiler is concerned, indistinguishable to a pointer to an array of characters. You use the "n" variant of strcat to limit it to just one character (plus an added NULL character) so it doesn't rely on the missing NULL termination.

For the second you could do:

int n = strlen(some_char_array);
some_char_array[n] = c;
some_char_array[n+1] = 0;

That just sets the Nth character in the target array to whatever is in c, then adds a new NULL termination character to the end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.