Strings.... so confused

Hi

Coming from javascript, I'm having a lot of trouble understanding strings in C.

If I want to create a string, I do it this way:

char myString[] = "My String";

Now, where I get confused is how to handle that variable. Say, I want to store that string in an array:

char myArray[] = {myString};

I think that's correct so far...but now if I want to refer to that element in the array:

Serial.print(myArray[0]);

I get a box, instead of "My String"

What am I missing here? Again, please remember I'm coming from Javascript.

Cheers.

I'm sorry, I can't tailor my responses for a particular language skill set. An array of strings looks like:

char myString[][maximumStringLength] = { "My String", "Your String" };
...
Serial.print(myString[0]);
Serial.print(myString[1]);
...

The reason the second dimension is a constant, is because the dimensions of the array must be known at compile time. The char strings can't be allocated dynamically in this case. Any strings that are shorter than the maximum just waste space.

Or

char * myString[] = {"Short String", "A much, much, much, much, much larger String"};

void setup()
{
  Serial.begin(115200);
  while (!Serial);
  Serial.println(myString[0]);
  Serial.println(myString[1]);
}

void loop()
{
}

Try turning up the compiler warning level in preferences. It will at least give you a cryptic error about what you're trying to do.

UKHeliBob:
Or

char * myString[] = {"Short String", "A much, much, much, much, much larger String"};

void setup()
{
  Serial.begin(115200);
  while (!Serial);
  Serial.println(myString[0]);
  Serial.println(myString[1]);
}

void loop()
{
}

Better:

const char * const myString[] = {"Short String", "A much, much, much, much, much larger String"};

void setup() {
  Serial.begin(115200);
  while (!Serial);
  Serial.println(myString[0]);
  Serial.println(myString[1]);
}

void loop() {
}

How about using

Safe, Robust, Debuggable String class for Arduino

or PString (a library you can instal with the library-manager

which give a bit more comfort about handling strings
best regards Stefan

SafeString V2 is now out. See the updated tutorial

V2 adds wrapping of char* and char[] in SafeStrings for safe processing that updates the original c-string directly.

You can also intermix calls to the SafeString with unsafe c-string method calls, but that is not advised. See the tutorial for details