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

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)

askedJul 31, 2020 at 12:42
will.mendil's user avatar

1 Answer1

1

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++) {    ...}
answeredJul 31, 2020 at 12:49
Majenko's user avatar
6
  • hum, ok interesting. But how would I calculate the length of any given array passed tomyFunction? In the example I only had mainMenu, but if I have multiple menus, I want to get its length programmiticallyCommentedJul 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.CommentedJul 31, 2020 at 12:58
  • really? so there is no function similar to go or python with len(x) or length(x) ?CommentedJul 31, 2020 at 13:01
  • 1
    No. There is no function like that. Simply because that is not how C works.CommentedJul 31, 2020 at 13:01
  • @will.mendil I have added some commonly used methods to my answer for you.CommentedJul 31, 2020 at 13:05

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy 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.