Given an array:
int array[] = {3, 1, 4, 1, 5};
And a function:
int funcao(int* argumento) {}
At the time you call the function, a Array decay for pointer occurs.
funcao(array);
And from that moment it is not possible to know the size of the array in any way. All that remains is a pointer to the first element. Usually one passes the size of the array 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 getting 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 . So:
int funcao(int (&argumento)[5]);
Now the size of the array is mandatory and it does make a difference. Decay does not occur here and you call the same as before: funcao(array)
. If you call with an array of size other than 5
there will be a compilation error.
Now is the magic of the templates. If there is only one acceptable length for the argument, let the compiler deduce this value from us:
template <typename T, int S>
int size(T (&arg)[S]) { return S; }
Given an array of S
elements of 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 inside 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 passed variable as an argument.