This line is calculating the size correctly:
int len = sizeof(vetor)/sizeof(int);
Better would be
int len = sizeof(vetor)/sizeof(vetor[0]);
because, in case you change the type of vetor
, will not be surprised by a bug difficult to perceive depending on the context.
Important to understand that the sizeof
is already solved by the compiler, because he simply already knows what was done in the variable definition, so if you need to know the size of a vector passed by parameter, the solution that remains is to always pass the vector and the size.
Back to your code, the problem is that you are calculating the size correctly, but you end up overwriting the value on this other line, this time with the pointer size:
tam = sizeof(vetor);
An output would be to calculate the size within the declaration scope, as you were already doing, and send the size to the median function.
See the difference:
#include <stdio.h>
#include <stdlib.h>
int retornaMediana(int *vetor, int tam){
// -- aqui você corre os ítens e calcula a mediana --
// return mediana;
printf("TESTE: %d, %d, %d\n\n",vetor[0],vetor[1],vetor[2]);
return tam;
}
void main(){
int vetor[] = {5,25,7,10,13,33,45,11,60};
int len = sizeof(vetor)/sizeof(vetor[0]);
int n = retornaMediana( vetor, len );
printf("TAMANHO = %d\n\n",n);
printf("TAMANHO = %d\n\n",len);
}
Here’s a demonstration on IDEONE.
And what result do you expect? Because?
– Maniero
What is the purpose of
n2 = sizeof(vetor) / sizeof(int);
?– gato
Please do not change the code in the question after it has been asked - one of the answers points to parts of the code that have changed and this makes it very difficult to keep track of anything.
– jsbueno
This function was to return tam, being the size of the vector, that is, a function that received a vector, and returned its size.
– Rafael Lopes
N2 was just a test in main to test if sizeof worked.
– Rafael Lopes
Do you want the vector size in bytes? That’s it?
– Intruso
I advise a reading of c-Faq, especially section 6.
– pmg