-2

Here is my simple code in c++..

int getSize(int *array){
int n = (sizeof(array)/sizeof(array[0]));
return n;

}

int main(){
    int array[4] ={1,2,3,4};
    std::cout<< getSize(array)<<std::endl; // prints 2 (first 2 elements)
}

I am a newbie in C++. I am not able to figure out the issue.

frazman
  • 32,081
  • 75
  • 184
  • 269

1 Answers1

2

That should be:

template <std::size_t N>
std::size_t getSize(const int (&)[N]){ return N; }
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • 2
    From the OP: "I am a newbie in C++." I.e. doesn't know templates or lambdas. If you're going to use advanced techniques, at least explain them to some degree. – David Nov 26 '14 at 08:09