0
int array1[] = {1, 2, 3, 4, 5};
int array2[] = {6, 7, 8, 9};

int *arrays[] = {array1, array2};

How to get length of the array1 and array2 from arrays? (arrays[0] length and arrays[1] length)

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • 3
    Can I interest you in our lord and savior, [`std::vector`](https://en.cppreference.com/w/cpp/container/vector)? (But jokes aside, is there a reason you're insisting on C-style arrays here instead of nice C++ vectors or `std::array`s?) – scohe001 Dec 23 '20 at 14:51
  • 2
    Save yourself a lot of pain here and use std::vector – mathematician1975 Dec 23 '20 at 14:51
  • 1
    pointers are not arrays. Arrays have a size, pointers to the first element of an array not. There are uncountable variations of this same problem, `std::vector` answers them all ;) – 463035818_is_not_an_ai Dec 23 '20 at 14:52
  • 1
    Prefer `std::array` if the size is fixed and set at compile time. That's an array that knows its size, and stays knowing its size (i.e. cannot decay to a pointer). There is no point incurring the dynamic allocation of `vector` if dynamic size is not needed. – underscore_d Dec 23 '20 at 14:54
  • @underscore_d: that won't work here -- you can't declare an array of `std::array`s of different sizes. – TonyK Dec 23 '20 at 18:44

1 Answers1

1

Not.
Pointers to datatype (inte.g.), which arrays decay to in this context, do not know about the size. It is similar to the problem that you cannot find the size within a function.
This means you need to know it, e.g. because you have in a second array the size information, or like in the case of 0-terminated characters sequences, a way to dermine the length from the content.

In order to be helpful, I join those (e.g. in the comments here), to use a C++ container class, most prominently the std::vector.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54