1

I want help on the following code

    int arr_1[] = {1, 2, 3, 4, 5};
    int arr_2[] = {6, 7, 8};
    int arr_3[] = {9, 10};

    int* arr[] = {arr_1, arr_2, arr_3, NULL};

    // print all the elements in array of arrays
    // printArray(arr);

    cout << sizeof arr_1;
    cout << sizeof *arr;

when I try the first cout, it gives me 20, which is correct. but when i try the second cout, it gives me 8 which is size of a pointer variable

why. !!

could anyone give me a correct explanation and how can i get the correct size in the second way i.e from array of arrays.

Thanks in advance

ppadhy
  • 332
  • 1
  • 3
  • 9

1 Answers1

2

To count the number of elements in a static array, you can create a template function:

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

For standard containers such as std::vector, the size() function is used. This pattern is also used with boost arrays, which are fixed size arrays and claim no worse performance to static arrays. The code you have in a comment above should be:

for ( std::vector::size_type i(0); i < entries.size(); ++i )
Liam Hardy
  • 246
  • 1
  • 7