Declare array of String

Hello, do you know how can I declare an array of the type String (notice the upper case S). I want to do something like this: String result[SENSOR_NUMBER]; where SENSOR_NUMBER is a constant. Thanks

Sounds like it should work. What is the value of SENSOR_NUMBER?

remember Strings and their manipulation are RAM hungry and an Arduino has 2K

Thanks for your reply. SENSOR_NUMBER is an int, I think value can be between 5 and 10 for example. I don't know why but declaring the array of sting in this way all the string are corrupted!

I prefer to use the String type because if not I must use somthing like this:

const int maxSize=10;
char result0[maxSize] = "uno";
char result1[maxSize] = "due";
char result2[maxSize] = "due";
char *pointer[3];

void setup() {
  
  Serial.begin(9600);
  pointer[0]=result0;
  pointer[1]=result1;
  pointer[2]=result2;

}

where maxSize make me lost a lot of memory. This depends on the fact that my strings are not constant and during the program they will be longer than the string declared for first. I also need to access strings in a loop and using this solution I have to adopt a pointer. So if it would be possible to declare a String vector it will be easier.

your question is about Strings and your code example is about char array’s. These are different datatypes.

Think you need something like

#define ARRAYSIZE 10
String results[ARRAYSIZE] = { "uno", "duo", "tri" };

void setup()
{
  Serial.begin(115200);
  for (int i =0; i< ARRAYSIZE; i++) Serial.println(results[i]);
}

void loop()
{
}
1 Like

If you are using string constants, the compiler can count so you don't have to set aside a fixed amount of space:

char *pointer[] = { "uno", "due",  "due"};

johnwasser: If you are using string constants, the compiler can count so you don't have to set aside a fixed amount of space:

char *pointer[] = { "uno", "due",  "due"};

this is possible only if I know the content when I am declaring the string

cantore: Thanks for your reply. SENSOR_NUMBER is an int, I think value can be between 5 and 10 for example. I don't know why but declaring the array of sting in this way all the string are corrupted!

Show us the code you're using that is corrupting the strings.

May be I have understood my problem. The way of declaring the array of string

String result[NUMBER_OF_SENSORS];

should be correct. The problem of string corruption should be that my sketch seems to use more than 2KB of ram. I need to use an arduino mega for testing the system.

Why use of pointers ??

1 Like