C ++ - Size of an array pointer

8

I have an array:

char *exemplo[] = {"item1", "item2", "item3"};

And a function:

void myFunc(**myArray)
{

}

So, I want a function that returns the size of this array that I passed as a parameter. For example if I pass the array exemplo the function should return 3 .

I know how to do this out of function, but when I pass as parameter it does not work.

    
asked by anonymous 16.05.2014 / 21:18

2 answers

5

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.

    
16.05.2014 / 21:33
0

In any case it becomes useless to pass the array by reference and still pass the number of elements of it in which you could simply pass the number of elements by another parameter.

Ideally, the function itself calculates the number of elements in the array, but this becomes impossible because the C passes only its pointer and the calculation with sizeof() or even with templates would not have the expected result.

I'm working on a code like this:

void main(void)
   char *menu[] = {"Incluir", "Remover", "Listar"};
   menupull(menu);
}

void menupull(char *a[])
{
  int nLen = LenArray( menu);
}

int LenArray(char *a[])
{
   int x = 0;
   while(*(a+x)){
     x++;
   }
   return x;
}
    
12.09.2016 / 07:28