Given an array:
int array[] = {3, 1, 4, 1, 5};
And a function:
int funcao(int* argumento) {}
The moment you call the function occurs a array decay for pointer.
funcao(array);
And from that moment it is not possible to know the size of the array at all. All that remains is a pointer to the first element. Usually the array size is passed as an additional argument. Note that the following also does not work:
int funcao(int argumento[]) {}
int funcao(int argumento[50]) {} // Você poder por qualquer número ali. É ignorado.
This is just another syntax for exactly the same thing. You’re taking a pointer as an argument.
However there is a way to resolve this. Instead of passing the argument as value, you can use a reference to an array. Thus:
int funcao(int (&argumento)[5]);
Now the size of the array is mandatory and it does make a difference. There is no decay here and you call in the same way as before: funcao(array)
. If you call with an array of size other than 5
there will be a compilation error.
This is where the templates magic comes in. If there is only one acceptable size for the argument, let’s make the compiler deduct that value for us:
template <typename T, int S>
int size(T (&arg)[S]) { return S; }
Given an array of S
elements of the type T
, the function will return the value of S
.
Example:
int array1[] = {3, 1, 4, 1, 5};
char* array2[] = {"item1", "item2", "item3"};
cout << size(array1) << endl; // 5
cout << size(array2) << endl; // 3
You can now do some computation within the function, since you have the size. But remember that you took the array by reference. So anything that changes in it will affect the variable passed as argument.
"I know how to do it out of function" just out of curiosity, how is it done? I thought it was impossible... But I’ve never worked in depth with C/C++, so I may (I must) be wrong.
– mgibsonbr
sizeof(example) / sizeof(*example)
– dromenox
Just out of curiosity, the function
main(int argc, char **argv)
remembers your problem.– Lucas Lima