Dimension of a vector passed by reference language C

Asked

Viewed 54 times

0

I would like to know how I discover the amount of positions that have a vector that has been passed by reference to the function, using the language C.

Example (Function prototype):

int Soma (int *vetorValores)
{
   int i;
   int tamVetor = ??
   int total = 0;

   for (i=0;i<tamVetor;i++)
   {
        total+=vetorValores[i];
   }
   return total;
}

1 answer

0


If you have the array in its scope, you can use the sizeof function to find the size in bytes and use division to calculate the amount of elements, as follows:

#define NUMERO_DE_ELEMENTOS 10
int arr[NUMERO_DE_ELEMENTOS];
tamanho_arr NumeroDeElementos= sizeof(arr)/sizeof(arr[0]);

Now, if you are passing the array as argument of a function (as you want), there is no way you determine the size using sizeof. You will have to calculate this before using your function and then pass this number of elements in some way, for example:

void suaFuncao(int* arr, int NumeroDeElementos)
{
  for(int i = 0; i < NumeroDeElementos; ++i) {

  /* faz o que você quiser aqui */
  arr[i] = /*...*/
  }
}
  • Thank you, dear. I ended up coming to this conclusion also after numerous researches. Rs

  • The second way was exactly what I did. Thanks for the tip.

  • I’m glad I helped! Thanks for the feedback!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.