Number of elements string array

How can I find the number of elementos of a parameter passed string array? I can't do
 
    unsigned int size = sizeof(kings) / sizeof(*kings);


and pass it as a parameter to the method, so I need to find a way to find it into the function itself.
The best answer is to use a vector (which has a .size() method).
If you want to use basic C-style arrays instead, then we usually pass in the size as another parameter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

template <typename T, size_t N>
size_t ArrSize(T(&)[N]) { return N; }

void f(int *a, size_t size) {
    for (size_t i = 0; i < size; ++i)
        std::cout << a[i] << '\n';
}

// Could do it with a templated function, but it creates a new function for every differently sized array.
template <typename T, size_t N>
void g(T (&a)[N]) {
    for (size_t i = 0; i < N; ++i)
        std::cout << a[i] << '\n';
}

int main() {
    int a[] = {1,2,3,4,5};
    f(a, ArrSize(a));
    g(a);
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
size_t string_size( const char* str)
{
    size_t count = 0;
    
    while( *str != '\0' )
    {
        str++;
        count++;
    }
    return count;
}

int main()
{
    char a_string[]{"A sample string"};
    
    std::cout << a_string << " Size: " << string_size(a_string) << '\n';
    return 0;
}
see if the ideas in here help:

http://www.cplusplus.com/forum/general/265321/
Topic archived. No new replies allowed.