aborocz
aborocz

Reputation: 199

c++ pass array to function question

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

Upvotes: 2

Views: 1754

Answers (5)

Constantinius
Constantinius

Reputation: 35039

In C++ it is considered a bad pratice to use raw arrays. You should consider using std::vector or boost::array instead.

It is difficult to calculate the size of an array if you do not keep track of the size or supply some sort of an guardian value at the end. In C-strings (not std::strings), for example, the '\0' character marks the end of the string (a char array).

Upvotes: 2

Nicolas Grebille
Nicolas Grebille

Reputation: 1332

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 guess it is because the function is inlined, but still it seems the array does not decay in this case. Can somebody explain why?

Upvotes: 1

Ruggero Turra
Ruggero Turra

Reputation: 17670

If you are using c arrays it's not possible because they're automatically casted to 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);

Upvotes: 0

sharptooth
sharptooth

Reputation: 170479

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.

Upvotes: 11

Seth Carnegie
Seth Carnegie

Reputation: 75130

This is (one of) the difference between arrays and pointers. Taking the size of an array results in its size in bytes, whereas taking the size of a pointer yields the size of pointers on that system. However, whenever you pass an array to a function, it decays to a pointer, the size of which is always the same no matter what type of pointer it is (4 on a 32 bit machine).

So technically, it's impossible to pass an array into a function since whenever you try, it becomes a pointer.

You'll need to pass the size of the array in to the function as well, or better yet if you can, use std::vector or std::array, or std::string if you're using the array as a C-style string.

Upvotes: 7

Related Questions