How to get size of String array

I am creating a string array in "Arduino" like this:

String commandList[] = {"dooropen", "doorlock"}; 

      

And in my code, I want to know the size of this array, and I don't want to determine the size of this array like the below code:

#define commandListArraySize 2

      

I am trying to get the size of this variable like this:

int size = sizeof(commandList);

      

But returned size

= 12

.

+3


source to share


4 answers


I like the Array Size pattern as it cannot be used with a pointer type:



// Solution proposed by @TylerLewis:
#define ARRAY_SIZE(x) sizeof(x)/sizeof(x[0])

// Template based solution:
template<typename T, size_t N> size_t ArraySize(T(&)[N]){ return N; }

int test(String * ptr);

void setup() {
  String arr[] = {"A", "B", "C"};
  Serial.begin(115200);
  Serial.println(ArraySize(arr));  // prints 3
  Serial.println(ARRAY_SIZE(arr)); // prints 3

  test(arr);
}

void loop() {
}

int test(String * ptr) {
  // Serial.println(ArraySize(ptr));  // compile time error
  Serial.println(ARRAY_SIZE(ptr));    // prints 0 as sizeof pointer is 2 and sizeof String is 6
}

      

+1


source


As long as you are creating the array that was created (you are not passing the array to the function) you can use this general macro:

#define ARRAY_SIZE(x) sizeof(x)/sizeof(x[0])

      



and use it like this:

String[] myStrings{"Hello", "World", "These", "Are", "Strings"};
for (size_t i = 0; i < ARRAY_SIZE(myStrings); i++) {
    Serial.println(myStrings[i]);
}

      

0


source


When you ask for the length of an array of strings, the sizeof method returns the length of all characters in the array. So let's count on this:

String commandList[] = {"dooropen", "doorlock"}; 
int a = 0;
int counter = 0;
while(counter < sizeof(commandList)){
  counter += sizeof(commandList[a]);
  a++;
}
int arrayLength = a;

      

0


source


String commandList[] = {"dooropen", "doorlock"}; 

int size = commandList.length;

      

0


source







All Articles