0

Possible Duplicate:
Sizeof an array in the C programming language?

    #include "stdafx.h"
    #include <string>
    #include <iostream>

    using namespace std;

    string a[] = {"some", "text"};

    void test(string a[])
    {
        int size_of_a = sizeof(a) /sizeof(a[0]);
        cout << size_of_a; 
    }
    int _tmain(int argc, _TCHAR* argv[])
    {
        test(a); //gives 0
        int size_of_a = sizeof(a) /sizeof(a[0]);
        cout << size_of_a; //gives 2
        return 0;
    }

as u can see in the comment test(a) gives 0 instead of 2 as i would expect. Could someone explain why and how could i correct it? thanks

Community
  • 1
  • 1
user1686999
  • 3
  • 1
  • 2

2 Answers2

1

When you pass an array to a function, it decays to a pointer to the first element of the array and so within your test(string a[]) function

sizeof(a);

actually returns the size of a pointer and not the size of your array.

mathematician1975
  • 21,161
  • 6
  • 59
  • 101
0

To prevent array decaing to pointer, you can pass reference to array to the function. But it causes types of array of function formal argument and actual argument must coincide (including their sizes). So you need to use template to make your function work with an array of any size:

template <int N>
void foo(const string (&a)[N])
{
    int size_of_a = sizeof(a) /sizeof(a[0]);
    cout << size_of_a; 
}
Lol4t0
  • 12,444
  • 4
  • 29
  • 65