Why is the size of the vector being changed in the function?

Asked

Viewed 52 times

1

Tanho comes as 2, when passed the tamVet function()

#include <stdio.h>

int tamVet(int *vet){
  int tam;
  tam = sizeof(vet) / sizeof(vet[0]);
  return tam; 
}

int main(void){
  int vetor[10];
  int tam = tamVetor(vetor);
  printf("%i", tam);
}

1 answer

5


This is because when you pass the vector to the function you only get the pointer to the first element, just when you do the sizeof takes pointer size and not vector size.

Something simple that demonstrates this:

#include <stdio.h>

void tamVet(int *vet){
  printf("\n%d", sizeof(vet)); // 8
}

int main(void){
  int vetor[10];
  printf("\n%d", sizeof(vetor)); // 40
  tamVet(vetor);
}

See this example working on Ideone

Please note that the values you see in the output may vary depending on the architecture, but it is guaranteed that the printf of vetor in the main gives you the size of the whole array in bytes, which will correspond to sizeof(int) * 10. And it is also guaranteed that in the function will see the size of a pointer to int, namely a int*.

Whenever you need the size of a vector in a function the solution is to pass the size to that function. This size is possible to calculate in the scope where the vector was built precisely with the calculation you made:

sizeof(vet) / sizeof(vet[0]);

But only in the scope where the vector was created.

If you look at the function qsort for example, which allows you to sort a vector, you will notice that the second parameter is actually the size of the vector.

  • But let’s say the function itself wants to know the size of the vector, how can I do ?

  • 2

    @Fernando It was as I answered. There’s no way to know, within the function only has a pointer to the first element in memory, so there’s no way. If the function wants to know the size, it has to receive it as parameter.

Browser other questions tagged

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