Writing to String Array

I am playing with a char* string array and trying to write values to it using some indexing.

This works the way I want :
char* myStrings[10]
myStrings[8] = “hi from 8”;

//it puts “hi from 8” in myStrings[8]

This works but not like I want :
char usbString[50];
myStrings[myStringsIndex] = usbString

// instead of of getting the value of usbString put into myStrings[myStringsIndex] I seem to be getting a pointer. I only want the value.
// with indexing this is bad. soon everything points at usbString rather then being equal to the value that was in usbString when I was indexing.

char* myStrings[10]={
  "This is string 1", "This is string 2", "This is string 3", "This is string 4", "This is string 5","This is string 6"};

int char_counter = 0;
int loopcounter = 0;
int incomingByte = 0;
int myStringsIndex = 0;

char c;
char usbString[50];


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

void loop(){
for (int i = 0; i < 10; i++){
   Serial.println(myStrings[i]);
   }
   
   if (loopcounter>2) {
     myStrings[8] = "bye from 8";
     } else {
       myStrings[8] = "hi from 8";
       }
   
loopcounter = loopcounter + 1;
if (loopcounter>4) {
   loopcounter = 0;
     }
     

if (Serial.available() > 0) {
  c = Serial.read();
  Serial.println("aread");
  if((c == '*')) {  // Line is complete. Then execute!
      usbString[char_counter] = 0;
      char_counter = 0;
      myStrings[myStringsIndex] = usbString;
      Serial.println("read *");
      myStringsIndex = myStringsIndex + 1;
      } else {
        usbString[char_counter++] = c;
        }
  }
if (myStringsIndex > 9) {
  myStringsIndex = 0;
  }

delay(1000);

}

I’m assuming that you want to put the strings you enter into the array (right?)

… And you want to do this using a character pointer array (right?)

So you enter a string into usbString and then tell the char pointer array the address of usbString.

Here is the problem- you are entering the address of the same place in memory over and over as you edit it with every input.

I’d advise you to look into 2 dimensional arrays and how to enter strings into them (strcpy). It looks to me that you want myStrings to be a 2 dimensional array, not a 1 dimensional pointer (so that your program remembers the strings entered).

If you were insistent on keeping myStrings as a pointer array, you could make usbString multidimensional, and point to different strings held within it. However, you might as well then get the info straight from usbString (and the pointer array becomes redundant).

Try searching for more info on “String arrays”

:slight_smile: