简体   繁体   中英

Issues with declaring and writing to arrays with Arduino and C++

I'm messing around with an Arduino board for the first time.

I have an array declared like this (I know don't judge me), it's for storing each character of the LCD as a sort of cache:

char* lcd_characters[] = {"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""};

Then later on I'm trying to write to a specific slot of the array, like this, to save that letter to it:

new_char = String(message.charAt(i));

...blah blah blah...

lcd_characters[pos] = new_char; << error here

However it is giving me this error:

error: cannot convert 'String' to 'char*' in assignment

The funny thing is when I do this (below) it do assign the letter to it, however I have a var which is a single letter but can't assign it.

lcd_characters[pos] = "H";

Can someone help me out please. Thanks. I'm brand new to C and been ok so far.

Basically I want an array of characters and then I want to write on the array positions with a new value.

Why does it even matter what type of string I'm writing to that array position, I should be able to write a number or boolean there too and call it later. Is there something wrong with the way the array is declared initially?

Edit:

I tried...

lcd_characters[pos] = new_char.c_str(); 

however that's giving me the similar error:

invalid conversion from 'const char*' to 'char'

Wtf? All I want to do is say this array position equals this new value. That's it. I've done this a million times in javascript, ruby, python (even php) etc. I just want to go, this array... x[12] equals my letter in new_char !!!! Ahh.

A few remarks:

  1. Are you using C or C++? String is a C++ class, but you are creating a an array of c strings ( char * ).

  2. You are creating an array of strings ( char* var[] equals to char** ), but your naming suggests you want an array of characters. A c string is basically an array of characters, so stick with that ( char * or char [] ).

I would recommend you go for only C code in this case:

char lcdChars[4] = {' ', ' ', ' ', ' '}; // init with spaces
lcdChars[2] = 'x'; // write x to position 3

Note: A string in C++ can output a C string ( char * ) by calling stringInstance.c_str() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM