I know this question has been asked a thousand times, but I can't find a solution for my case.
I what to get the length of a string array in a given function. This is for an arduino board.
#define LEN(x) sizeof(x)/sizeof(x[0])const char* mainMenu[] = {"FirstWord", "SecondWord", " "}; void myFunction(const char** m) { int a = LEN(m); /* Do something */};void setup(){ myFunction(mainMenu);};TheLEN(m) works fine in thesetup() function. But inmyFunction() it either gives me 1 (i guess the length of the pointer) or 9 (length of the 0th element of the array)
1 Answer1
The problem is that LEN is evaluated locally for each usage replacing it with the content. InmyFunction the parameter being passed to it is a pointer, not the array.
You need to evaluate the size once and once only in the context where the array hasn't collapsed into a pointer. That is usually done immediately where the array is defined:
const char* mainMenu[] = {"FirstWord", "SecondWord", " "}; #define MAINMENU_LEN (sizeof(mainMenu) / sizeof(mainMenu[0]))BecausemainMenu is a global it's always available, and when you require the length you get the length of the global array.
If you want to keep things local you will have to pass the number of elements in the array as a parameter to the function that uses that information.
myFunction(mainMenu, MAINMENU_LEN);Another common alternative is to have some "end of array" marker and you loop through your array until you find that marker (that's how strings work - with\0 for the end of array marker):
const char* mainMenu[] = {"FirstWord", "SecondWord", " ", 0};Then:
for (int i = 0; m[i] != 0; i++) { ...}- hum, ok interesting. But how would I calculate the length of any given array passed to
myFunction? In the example I only had mainMenu, but if I have multiple menus, I want to get its length programmiticallywill.mendil– will.mendil2020-07-31 12:53:13 +00:00CommentedJul 31, 2020 at 12:53 - You can't. You have to calculate it somewhere where the array is still an array (the point where it's defined) and pass that value as a parameter.Majenko– Majenko2020-07-31 12:58:46 +00:00CommentedJul 31, 2020 at 12:58
- really? so there is no function similar to go or python with len(x) or length(x) ?will.mendil– will.mendil2020-07-31 13:01:16 +00:00CommentedJul 31, 2020 at 13:01
- 1No. There is no function like that. Simply because that is not how C works.Majenko– Majenko2020-07-31 13:01:55 +00:00CommentedJul 31, 2020 at 13:01
- @will.mendil I have added some commonly used methods to my answer for you.Majenko– Majenko2020-07-31 13:05:03 +00:00CommentedJul 31, 2020 at 13:05
Explore related questions
See similar questions with these tags.
