Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How is it possible to pass an array parameter to a function, and calculate the size of the array parameter? Because every time i try to calculate it, the return value is always 4.

Thanks the fast replies. I'm going to pass the size of the array as well then. Or i give a shot to vectors. Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
622 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can do it using templates as described here:

template<size_t Size>
void AcceptsArray( ParameterType( &Array )[Size] )
{
    //use Size to find the number of elements
}

it is be called like this:

ParameterType array[100];
AcceptsArray( array ); //Size will be auto-deduced by compiler and become 100

The only drawback is that you now have a templated function and that increases code bloat. This can be addressed by redirecting the call to a non-templated function that accepts the address of the first element and the number of elements.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...