About Char Array variable assignment

Hi,
I write a small piece of program,and encountered a problem,see below,
the char array "line2" can not be assigned "OFF".The IDE warns me "expected primary-expression before ']' token",I think I make some syntax error,but I don't know why.
hope for correct it,thanks a lot.

maybe something more like this..

char line1[10];
char line[10];

int humi = 85;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  memset(line1,0,sizeof(line1));//erase
  strcpy(line1,"ON");
  Serial.println(line1);
  memset(line,0,sizeof(line));
  sprintf(line,"%d",humi);
  Serial.println(line);


}

void loop() {
  // put your main code here, to run repeatedly:

}

cpp/string/byte

good luck.. ~q

Or use strcpy() or even better strncpy().

strcpy(line2, "0n");

strncpy(line2, "Off", 4);  // better.  avoids buffer overrun

Images of code are sub optimal. Please read the forum guidelines to see how to properly post code and some good information on making a good post.

Use the IDE autoformat tool (ctrl-t or Tools, Auto format) before posting code in code tags.

Please post code as text in a post using code tags (see How to get the best out of this forum).

char line[] = "" creates a character array with 1 element (the terminating '\0'). Next trying to copy 3 or 4 characters into that will result in disasters.

So the first thing to do is create an array that is big enough to hold the biggest text that you need plus one extra character. That is what @qubits-us's first lines do.

And next you can use the various functions for c-strings as indicated above.

@qubits-us, I think that the memset() is redundant :wink:

Yes, extremely..
Was there to help learn only..

sorry.. ~q

Hello

Otherwise you can use String variable:

char line2[10];
String line2str;
if (.....)
{
  line2 = "ON";
}
line2str.toCharArray(line2, sizeof(line2));
displayled(line2, 1000);

No need to be sorry.

The evils of Arduino Strings.

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