John Ranger
John Ranger

Reputation: 633

Arduino; dynamically getting elements of array; Array is of type struct which includes different size strings

in Arduino C++ I have the following struct:

struct acceptedCommand {
 String Command;
 int   switchcase;
};

Then I initialise an Array of the above struct like this:

const acceptedCommand acceptedCommands[] = { 
  {"set-amountofcells", 1}, 
  {"set-cell-min-voltage", 2},
  {"set-cell-max-voltage", 7}
  ...
};

Desired result: I want to dynamically return the number of elements in this array.

What I already tried: I cannot use the SizeOf function because this returns only the total amount of bytes used of the array.

I also cannot divide the value returned by SizeOf by the size of the struct because the size of each element of the array is different (because of the different length of the string).

So how can I get the number of elements in the acceptedCommands[] array dynamically?

Upvotes: 1

Views: 694

Answers (2)

Killzone Kid
Killzone Kid

Reputation: 6240

sizeof(acceptedCommands)/sizeof(acceptedCommand) should give you the number of structs in the array, thus the number of commands.

You might think your struct is variable size but it is not, sizeof String is known at compile time even if the length of its char array is different, because String will be an object probably containing a pointer to char array among other things and sizeof pointer is known at compile time.

Upvotes: 1

thilinaur
thilinaur

Reputation: 141

You'll need to use vectors instead of arrays. Use Standard C++ for Arduino. Then you'll be able to use stl vector in Arduino.

Upvotes: 0

Related Questions