0

This problem has been bugging me since forever. I have an array and in the scope of its declaration, I can use the sizeof operator to determine the number of elements in it but when I pass it to a function, it interprets as just a pointer to the beginning of the array and the sizeof operator just gives me the size of this pointer variable. Like in the following example,

#include<iostream>
int count(int a[]){
    return (sizeof(a)/sizeof(int));
}
int main(){
    int a[]={1,2,3,4,5};
    std::cout << sizeof(a)/sizeof(int) << " " << count(a) << std::endl;
    return 0;
}

The output of the code is 5 2. How so I pass an array to the function so that I could determine its size by the use of only the sizeof operator and won't have to pass on the extra size as a parameter to this function?

2
  • 4
    Consider also std::array (you'll need a C++11 compiler). Commented Dec 29, 2011 at 20:02
  • 1
    If you don't have C++11 you can just use boost::array, which is more or less the same thing Commented Dec 29, 2011 at 20:25

2 Answers 2

6
template<size_t N>
int count(int (&a)[N])
{
    return N;
}
Sign up to request clarification or add additional context in comments.

12 Comments

thanx Benjamin. can u tell me how to do the same in c.
@sidharthsharma: No, I cannot.
@sidharth sharma: cannot be done as you describe in C. Arrays decay to a pointer when passed as a function argument (and in many other cases). So you will need to explicitly pass the size.
@sidharth Wait, you asked a question about C++, and you want an answer in C?
@sidharthsharma This is exactly why writing "C/C++" and confusing the two languages is a bad idea.
|
1

You cannot do that. There is no way of passing an array that will make it carry its size information with it. You have to do it yourself. You have to pass the count as an additional parameter.

2 Comments

This isn't true - see Benjamin's answer
@awoodland But, this is cheating, isn't it? It only works if the explicitly dimensioned array declaration is in scope. It will not work if I have int myfunction( int[] a ).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.