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

1

Tanho comes as 2, when passed the tamVet ()

#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);
}
    
asked by anonymous 10.08.2018 / 01:13

1 answer

5

This happens because when it passes the vector to the function it only gets the pointer for the first element, so when it does the sizeof it picks the size of the pointer and not the size of the vector.

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 printf vetor no main gives you the size of the entire vector in bytes, which will correspond to% with%. And it is also guaranteed that in the function you will see the size of a pointer to sizeof(int) * 10 , that is 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 did:

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

But only in the scope where the vector was created .

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

    
10.08.2018 / 01:34