Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sizeof on arrays passed as parameters [duplicate]

Possible Duplicate:
Sizeof array passed as parameter

Given the function below I understand that sizeof returns the size of the pointer of the type in the array.

int myFunc(char my_array[5])
{
    return sizeof(my_array);
}

However calling sizeof on an array not passed as a parameter normally returns the sizeof the array.

What causes this inconsistency? What is the best way of getting the size of an array when it is passed as a parameter?

like image 927
Jim Jeffries Avatar asked Feb 25 '12 12:02

Jim Jeffries


People also ask

Can you use sizeof on an array?

We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);

How do you pass the size of an array as a parameter?

The function clear() uses the idiom sizeof(array) / sizeof(array[0]) to determine the number of elements in the array. However, array has a pointer type because it is a parameter. As a result, sizeof(array) is equal to the sizeof(int *) .

Can you pass arrays as parameters?

Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.

Can the sizeof operator be used to tell the size of an array passed to a function?

Using sizeof directly to find the size of arrays can result in an error in the code, as array parameters are treated as pointers.


2 Answers

What causes this inconsistency?

The name of the array decays as an pointer to its first element.
When you pass an array to an function, this decaying takes place and hence the expression passed to sizeof is a pointer thus returning pointer size.

However, an array passed to sizeof always returns size of the array because there is no decaying to an pointer in this case.

What is the best way of getting the size of an array when it is passed as a parameter?

Don't pass them by value, pass them by reference or
Pass size as an separate argument to the function.

like image 142
Alok Save Avatar answered Nov 03 '22 00:11

Alok Save


You have to pass the array by reference; you cannot pass arrays by value (they decay into pointers to the first element):

int myFunc(char const (& my_array)[5])
{
    return sizeof(my_array);  // or just "return 5"
}

In case that you want to call this function with a reference to lots of different local arrays, you can use a function template instead to have the array size deduced:

template <unsigned int N>
int myFunc(char const (& my_array)[N])
{
    return sizeof(N);         // or "return N"
}

You should really make the functions return an unsigned int or an std::size_t, though. In C++11, you can also declare them as constexpr.

like image 42
Kerrek SB Avatar answered Nov 02 '22 23:11

Kerrek SB