-1

I'm trying to find the number of elements in the menu1 array by using the current_menu variable but I'm not getting anywhere. I'm getting lost in a pointer inception kind of thing...

const char *menu1[] = { "Menu title", "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9" };

const char * *current_menu = menu1;

I tried:

sizeof(*current_menu) / sizeof(*current_menu[0])
sizeof(*(*current_menu)) / sizeof(*(*current_menu)[0])

But nothing's working... How can I do it?

Any help would be much appreciated!!

Mugen
  • 21
  • 5
  • Because of how pointers work, you can't get the number of elements in your array this way. C APIs typical store both the pointer and the size of the array for this reason. But you have tagged this question C++, so you should try using `std::array` or `std::vector` instead. For `std::array`, the size is part of the type, `std::vector` has a size member function. – Mansoor Feb 15 '21 at 17:30
  • @churill It does but I can't wrap my head around the explanation (sorry)... I'm not sure I understand how to code it. – Mugen Feb 15 '21 at 17:31
  • The first step to understand this could be to mentally seperate pointers and arays. Pointers can point anywhere. For example to the first element of an array. Or to the second element, or right in the middle of an array or to a single value. Or at a random location or at nothing (`nullptr`). `sizeof` is evaluated at _compile time_. The size of an pointer is fixed at compile time, no matter where it will point at runtime. – Lukas-T Feb 15 '21 at 17:35

1 Answers1

2

The size of a pointer pointing to an element of an array is always the same regardless of how many elements there are in the array. Also, the size of the pointed object is always the same regardless of the number of siblings. As such, there is nothing you can do with sizeof to get the length of the array using the pointer.

In general, there is no way to get the number of elements in an array based on a pointer to an element of that array. The number of elements is encoded in the type of the array, so you can get the length if you have access to the array object itself. The standard library has a helpful function template for that purpose:

std::size_t length = std::size(menu1);
eerorika
  • 232,697
  • 12
  • 197
  • 326