How to determine the length of a global array in a function on Arduino?

Is this possible in C ++ (on Arduino)?

#include "stdio.h" String str = "foo"; int i[strLength()]; // <- define length of array in function int strLength() { return str.length(); } int main(void) { ... } 

Thank you in advance!

+4
source share
3 answers

No. You will need i to be a pointer and allocate an array in main :

 int *i = NULL; // etc. int main(void) { i = (int*) malloc(sizeof(*i)*strLength()); // etc. } 
+2
source

If you are using C ++, the correct solution is std :: vector. You will need to look at the docs for std :: vector, but here is the conversion of your code to std :: vector.

Then you use std :: vectors the same way you use regular arrays using the [] operator.

 #include <cstdio> #include <vector> String str = "foo"; int strLength() { // Needs to come before the use of the function return str.length(); } std::vector<int> i(strLength() ); //Start at strLength int main(void) { ... } 
+3
source

I know that this is not what you hoped for, but I would just do something ridiculous:

 String str = "foo"; #define MAX_POSSIBLE_LENGTH_OF_STR 16 ... int i[MAX_POSSIBLE_LENGTH_OF_STR]; 

The idea is that you allocate more space for the array than you really need, and just avoid using extra parts of the array.

Alternatively, if you are not going to change the definition of str in your source code very often, you can save some RAM by doing the following:

 String str = "foo"; #define LENGTH_OF_STR 3 ... int i[LENGTH_OF_STR]; 
+1
source

Source: https://habr.com/ru/post/1385775/


All Articles