Explain SizeOf Number element array

Hello,for those who knew how to return number of elements array usually use 'sizeof( arrayNumber ) / sizeof( arrayNumber[ 0 ] )'. However, I don't quite understand the code behind it. Why need to divide into first element of the array ?

1
2
3
4
5
6
int main()
{
int arrayNumber[] = {1,2,3,4,5,6,7,8,9};
int numberElementArray = sizeof( arrayNumber ) / sizeof( arrayNumber[ 0 ]);
cout << "Number of element in arrayNumber is: " << numberElementArray;
}


Output
 
Number of element in arrayNumber is: 9
Last edited on
sizeof(arrayNumber) is the total number of bytes occupied by the array in memory, which is not 9 in this case. sizeof(arrayNumber[0]) is the size of one element in the array, which is not 1 in this case.

Try printing out each size separately and do some mental math.

By the way, this is a bad way to detect the number of elements in an array - prefer instead to use something specifically designed to do that:
http://en.cppreference.com/w/cpp/types/extent
Or in C++03:
1
2
3
4
5
6
7
template<typename T, std::size_t N>
std::size_t sizeof_array(T (&t)[N])
{
    return N;
}
//...
std::cout << sizeof_array(arrayNumber) << std::endl;
http://ideone.com/PPOyuM
Last edited on
Use std::extent<> when dealing with types.

Prefer the constexpr version of the C++03 template when dealing with objects.

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

template < typename T, std::size_t N >
constexpr std::size_t size( T(&)[N] ) { return N ; }

int main()
{
    const int a[] = { 0, 1, 2, 3, 4 } ;

    int b[ size(a) ] {} ;

    int c[ std::extent< decltype(a) >::value  ] {} ;

    int d[ size(a) ][ size(b)*2 ][ size(c)*3 ] {} ;

    std::cout << size(d) << ' ' << std::extent< decltype(d) >::value << '\n' ;
    std::cout << size( d[0] ) << ' ' << std::extent< decltype(d), 1 >::value << '\n' ;
    std::cout << size( d[0][0] ) << ' ' << std::extent< decltype(d), 2 >::value << '\n' ;
}

http://coliru.stacked-crooked.com/a/2609822ffc4b774d
Topic archived. No new replies allowed.