how to calculate no of elements in an array

for example
char *a[]={"abc","def","ghi"};
pls help me!
YOu can do this only if array was not passed into any function, because arrays degenerate to pointers when you do that.

Safe C++ way to do it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

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

int main()
{
    //Usage
    const char *a[]={"abc","def","ghi"};
    std::cout << array_size(a);
}
3
http://coliru.stacked-crooked.com/a/61a4f0d7be5271ea
thanks a lot i got this in another way


char *c={"abc",def"};
return sizeof(c)/sizeof(c[0]);


output:
2

thanks a lot i got this in another way
Note that this way requires constant programmer attention as it does not prevent array from decaying to pointer: http://coliru.stacked-crooked.com/a/a758ffb73dd09b1c
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

size_t array_size(const char* c[])
{
    return sizeof(c)/sizeof(c[0]);  
}

int main()
{
    //Usage
    const char *a[]={"abc","def","ghi"};
    std::cout << array_size(a);
}
1


you can also use std::array template.
Topic archived. No new replies allowed.