C ++ pass array for asking a question

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

Thanks for the quick answers. I am also going to pass the size of the array. Or I give a shot at vectors. Thanks

+2
source share
5 answers

This is (one of) the difference between arrays and pointers. Taking the size of the array results in its size in bytes, while the size of the pointer gives the size of the pointers in this system. However , whenever you pass an array to a function, it splits into a pointer whose size is always the same no matter what type of pointer it is (4 on a 32-bit machine).

So it is technically impossible to pass an array to a function, because whenever you try, it becomes a pointer.

You also need to pass the size of the array to the function, or, if you want, even better, use std::vector or std::array or std::string if you use the array as a C-style String.

+7
source

You can do this using templates as described here :

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

it is 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 boilerplate function, and this increases the bloat of the code. This can be eliminated by redirecting a call to a non-templated function that accepts the address of the first element and the number of elements.

+11
source

In C ++, it is considered the wrong procedure to use raw arrays. Instead, use std::vector or boost::array .

It is difficult to calculate the size array unless you are tracking the size or setting some kind of guardian value at the end. For example, in C-lines (not std::strings ) the character '\ 0' marks the end of the line ( char array).

+2
source

This works with g ++:

 template <typename T> std::size_t size_of_array (T const & array) { return sizeof (array) / sizeof (*array); } int main () { int x [4]; std::cout << "size: " << size_of_array (x) << '\n'; } 

I assume this is because the function is built-in, but still it seems that the array will not decay in this case. Can someone explain why?

+1
source

If you use c-arrays, this is impossible, because they are automatically passed to the pointer when passing it to a function. So 4 is the size of the pointer.

Solution: use std::vector

 #include <vector> int carray[] = {1,2,3,4}; std::vector<int> v(carray, carray + sizeof(carray)/sizeof(int)); my_function(v); 
0
source

Source: https://habr.com/ru/post/895757/


All Articles