1

If I have the following function in C++:

void functionName(HANDLE arr[100])
{
}

HANDLE hHandles[100];
functionName(hHandles);

Is there any way to know the size of 'arr' inside the functionName? (Without hardcoding it there)

4
  • 1
    Not without passing it in as an arg, no. That is why std containers store the array size. Commented Feb 16, 2012 at 18:28
  • related FAQ Commented Feb 16, 2012 at 18:30
  • @crush: if you change the function parameters it can be done. Commented Feb 16, 2012 at 18:51
  • possible duplicate of determine size of array if passed to function Commented Feb 16, 2012 at 21:37

4 Answers 4

8

Use template to catch the N in T[N]

template <size_t N>
void function(HANDLE (&arr)[N]) 
{
  std::cout << N << " is here\n";
}
Sign up to request clarification or add additional context in comments.

2 Comments

OK, yeah, this one uses templates though.
you dont have many options anyway. The fact the size of an array is part of the array type in C++ is a very strong informations. Not using it result in subpar solution.
1

No. Unless you have put a delimiter at the end yourself before passing. In case of strings (which are character arrays)the delimiter is the null character '\0' so the size can be checked. But normally for arrays this can't be done.

1 Comment

Terminator is a good suggestion, but there's several ways to do this.
0

Consider sending the size as a separate parameter instead.

void functionName(HANDLE arr[100], size_t size)
{
}

1 Comment

Consider instead using std::vector.
0

You could also use a global variable or a class attribute.

size_t size = 100;
void functionName(HANDLE* arr)
{
//size will be visible here and in any other
// functions and you can change its value during run-time

}

Comments

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.