Reputation: 2134
When I run this code:
#include <iostream>
using namespace std;
void PrintLengthOfArray(double arr[])
{
int total_bytes = sizeof(arr);
int data_type_bytes = sizeof(arr[0]);
int length = total_bytes / data_type_bytes;
cout << "method 2: \n";
cout << "total_bytes = " << total_bytes << "\n";
cout << "data_type_bytes = " << data_type_bytes << "\n";
cout << "length = " << length << "\n";
}
int main()
{
double arr[3] = {1,2,3};
int total_bytes = sizeof(arr);
int data_type_bytes = sizeof(arr[0]);
int length = total_bytes / data_type_bytes;
// first method
cout << "method 1: \n";
cout << "total_bytes = " << total_bytes << "\n";
cout << "data_type_bytes = " << data_type_bytes << "\n";
cout << "length = " << length << "\n\n";
// second method
PrintLengthOfArray(arr);
}
I get:
method 1:
total_bytes = 24
data_type_bytes = 8
length = 3
method 2:
total_bytes = 8
data_type_bytes = 8
length = 1
That is, it's like the total_bytes = sizeof(arr)
statement in the function is only computing the size of an individual element, or just arr[0]
. What's going on?
Upvotes: 1
Views: 2272
Reputation: 56547
In the second method, you pass the array by value to your function. It decays to a pointer, hence the size is that of the pointer, in your case 8 bytes. Note that a function declaration
f(double arr[])
or even
f(double arr[3])
is translated by the compiler into
f(double*)
The only meaningful way of passing an array to a function and retaining its size is to pass by reference, e.g.
void f(double (&arr)[3])
{
std::cout << sizeof arr << std::endl; // displays 3 * sizeof(double)
}
In case you want to be able to pass arbitrary-length arrays, I recommend passing by reference via a templated function:
template<typename T, size_t N>
void f(T (&arr)[N])
{
// N gives you the size in the body
}
If you still want to pass by value, then the only way of "detecting" its size is to pass an additional parameter to your function that represents the size of the array. However this may give rise to lots of headaches, and it is prone to errors. You are probably better with std::vector
or std::array
instead.
Upvotes: 6