2

Why I'm getting this error?

invalid conversion from 'const char*' to 'char' [-fpermissive]

Here is my simple sketch:

const char data = "should";

//I have also tried:
//const char* data = "should";

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.print("this " + data + " work");
}
VE7JRO
  • 2,515
  • 19
  • 27
  • 29
Kirill
  • 151
  • 2
  • 2
  • 12

2 Answers2

4
const char data = "should";

In this case data is a single character, not a string. So it can store 's' but not "should".

Serial.print("this " + data + " work");

No, that will never work, even if you get your data types correct. You do not concatenate strings like that. All you are doing is attempting to add the addresses of two string literals to the address of a string constant. If that were possible (the compiler doesn't let you) you'll get gibberish (or a crash) as it tries to print out whatever is at that address.

Instead break it down:

Serial.print("this ");
Serial.print(should);
Serial.print(" work");
Majenko
  • 105,851
  • 5
  • 82
  • 139
1

A char can only store one character.

and const char* data can store a pointer to a string.

You can copy it with strcpy:

const char* data = malloc(7);
if (data != 0)
{
    strcpy(data, "should");
}

This will create 7 bytes, which can store "should" (adding 1 byte extra for the \0 byte to denote the end of a string.

However, in your case you can create a const string like:

const char data[7]="should";

or

const char data[]="should";
Michel Keijzers
  • 13,014
  • 7
  • 41
  • 58