1

I have two char pointer arrays:

char* mainMenu[] = {"Start", "Mode"};
char* subMenu[] = {"Mode1", "Mode2", "Mode3"};

I put both arrays in an array containing pointer to pointer: char **menus[] = {mainMenu, subMenu};

Now I'd like to get the size of the subMenu array by using menus.

With subMenu it works:

int num = sizeof(subMenu)/sizeof(subMenu[0]);  // num = 3

But I'd like to do this with menus, i tried:

int num2 = sizeof(*(menus[1]))/sizeof(*(menus[1]))[0];  // num2 = 2

What do i have to do with menus to get 3 as a result?

3
  • 1
    printf("%zu\n", sizeof menus / sizeof menus[0]); outputs 2, which is the same way you did it before. Commented Jun 2, 2021 at 9:49
  • yes i know, but my question is, how can i get 3 as a result using sizeof and menus. (don't want to get the result by using subMenu) Commented Jun 2, 2021 at 10:02
  • 1
    You cannot find the length of an array by dereferencing a pointer. It is impossible to know how many valid elements there are. The lengths will have to part of the containing structure too. Commented Jun 2, 2021 at 10:13

2 Answers 2

2

I was thinking about de-reference. Something like sizeof(*(menus[1]))/sizeof(*(menus[1])[0]). Why doesn't it work ?

It doesn't work because menusis not an array of arrays but an array of pointers. The submenu identifier used to initialize menus is a taken as a pointer, not an array.

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

Comments

0

For any array in C, this holds:

#define SIZE_OF_ARRAY(arr) (sizeof (arr) / sizeof (arr)[0])

Doesn't matter if it's an array of char*, char** or some other type. With your arrays:

char* mainMenu[] = {"Start", "Mode"};
char* subMenu[] = {"Mode1", "Mode2", "Mode3"};
char **menus[] = {mainMenu, subMenu};
printf("mainMenu %zu\n", SIZE_OF_ARRAY(mainMenu));
printf("subMenu %zu\n", SIZE_OF_ARRAY(subMenu));
printf("menus %zu\n", SIZE_OF_ARRAY(menus));

5 Comments

yes i know, but my question is, how can i get 3 as a result using sizeof and menus. (don't want to get the result by using subMenu)
@Dede_ You can't get the result 3 because it contains 2 items. If you want to de-reference it to get the size of its members you have to do something less "raw", for example by creating arrays of structs that store both the string and its size.
Yes, i was thinking about de-reference. Something like sizeof(*(menus[1]))/sizeof(*(menus[1])[0]). Why doesn't it work ?
@Dede_ Because the fact that mainMenu etc are arrays is lost when set a char** to point at them. A char** can only be used to point at pointers, it is not an array and knows nothing of arrays. But sizeof needs an array to work.
@Dede_ See my first comment.

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.