1

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?

0

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 - you are right - this gives back the correct amount of array entries. Thanks for correcting my wrong thinking :-)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.