0

My code is quite simple:

#include <iostream>
using namespace std;
int test(int b[]){
    cout<<sizeof(b)<<endl;
    return 1;

}
int main(){
    int a[] ={1,2,3};
    cout<<sizeof(a)<<endl;
    test(a);
    system("pause");
}

output of this code is:

12
4

which means that when a[] is transfered as a parameter to function test(),is has been deteriorated as a int *, so the output of size(b) is 4 ,instead of 12.So ,my question is , how can I get the actual length of b[] inside function test() ?

wuchang
  • 3,003
  • 8
  • 42
  • 66
  • hi, IIRC you cannot because the function parameter is a pointer. if you really need this feature you could use `std::array` or `std::vector` – Massimo Costa Sep 09 '14 at 14:30

1 Answers1

6

You could do this with a function template:

#include <cstddef> // for std::size_t

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

then

#include <iostream>

int main()
{
    int a[] ={1,2,3};
    std::cout << size(a) << std::endl;
}

Note that in C and C++, int test(int b[]) is another way of saying int test(int* b), so there is no array size information inside of the test function. Furthermore, you could use standard library container types which know their size, such as std::array.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480