0

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);
};

The LEN(m) works fine in the setup() function. But in myFunction() it either gives me 1 (i guess the length of the pointer) or 9 (length of the 0th element of the array)

1

The problem is that LEN is evaluated locally for each usage replacing it with the content. In myFunction 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]))

Because mainMenu 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++) {
    ...
}
| improve this answer | |
  • 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 programmitically – will.mendil Jul 31 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 Jul 31 at 12:58
  • really? so there is no function similar to go or python with len(x) or length(x) ? – will.mendil Jul 31 at 13:01
  • 1
    No. There is no function like that. Simply because that is not how C works. – Majenko Jul 31 at 13:01
  • @will.mendil I have added some commonly used methods to my answer for you. – Majenko Jul 31 at 13:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.