How do I find out the size of an array passed to a function?
You need to determine the size of the array passed to the function. I tried it like this:
void foo(int* Array)
{
const unsigned int SIZE = sizeof(Array)/sizeof(int);
}
But in SIZE
, 1 is stored, regardless of the size of the array. You can, of course, pass its size to the function along with the array, but maybe there is a more elegant solution?
P.S.: By the way, I noticed something strange. I ran this program through Visual Studio and Qt. In VS, SIZE
stores 1, and in Qt 2.
1 answers
You have a function parameter foo
declared as a pointer of type int *
void foo(int* Array);
^^^^^^^^^^
Therefore, inside the function, the expression
sizeof(Array)/sizeof(int)
Equivalent to the expression
sizeof(int *)/sizeof(int)
If, for example, the size of a pointer, that is, of type int *
, is 8 bytes, and the size of type int
is 4 bytes, then you will end up with 2. If the size of the int
type is also 8 bytes (64-bit OS), then you will end up with 1.
But even if you declare this function as
void foo(int Array[]);
Or even so
void foo(int Array[10]);
Still, the function parameter is implicitly converted to a pointer to an array element. That is, these two function declarations declare the same function and are equivalent to the following declaration
void foo(int* Array);
So inside the function, you'll be dealing with the pointer again.
When an array is passed by value, you should also declare a second parameter that sets the size of the array.
Or the array should have some boundary element with a unique value that can be used to determine the number of actual elements, as is the case, for example, with strings, when the strings end with a zero, that is, with the symbol '\0'
.
That is, in general, you should declare the function as
void foo(int* Array, size_t n);
Where n
is the size of the array.
Another approach is to declare a parameter as a reference to an array. In this case, the length of the array will be known inside the function. For example
void foo( int ( &Array )[10] )
{
const size_t = sizeof( Array)/ sizeof( *Array );
}
The disadvantage of this declaration is that this function can only deal with arrays of the size specified in its parameter.
To get around this limitation, you can declare a template function. For example,
template <size_t N>
void foo( int ( &Array )[N] )
{
const size_t n = N;
}
In this case, the compiler, using the template, will create as many functions as arrays of different lengths were used as an argument.