i have something like this
char * array[] = {"one","two","three","five"};
how can I get its length (which is 3 here).
if I use strlen()
then I get the length of "one".
Asked
Active
Viewed 671 times
-2

Vlad from Moscow
- 301,070
- 26
- 186
- 335

lag123
- 21
- 1
-
4What does "length" mean, for an array of pointers, and how did you arrive at the conclusion that this array's "length" is 3? I count four pointers in this array. Furthermore, this is not even valid C++, since in C++ string literals are constant, and every self-respecting C++ compiler will refuse to compile the shown code. – Sam Varshavchik Jun 20 '21 at 13:23
-
2Does this answer your question? [Determine the size of a C++ array programmatically?](https://stackoverflow.com/questions/197839/determine-the-size-of-a-c-array-programmatically) – MatG Jun 20 '21 at 13:25
-
Be careful. Once you pass array to a function it will decay to a pointer and the size information will be lost inside the function. This is one reason to use std::array<> or std::vector<> instead. – drescherjm Jun 20 '21 at 13:59
2 Answers
1
For starters you have to use the qualifier const in the array declaration.
const char * array[] = {"one","two","three","five"};
To get the number of elements in the array you can write
size_t n = sizeof( array ) / sizeof( *array );
If your compiler supports the C++ 17 Standard then you also can write
#include <iterator>
//...
size_t n = std::size( array );
Before the C++ 17 Standard you can use the structure std::extent
.
For example
#include <type_trats>
//...
size_t n = std::extent<decltype( array )>::value;

Vlad from Moscow
- 301,070
- 26
- 186
- 335
0
with c++17 : the std::size() in the iterator header:
Return value :
The size of c or array.
#include <iostream>
#include <iterator>
int main(int argc, char *argv[])
{
int arr[] = { -5, 10, 15 };
std::cout << std::size(arr) << '\n';
...

ΦXocę 웃 Пepeúpa ツ
- 47,427
- 17
- 69
- 97