Calculate vector size

1

How to calculate the size of the vector?

My code:

#include <stdio.h>
#include <stdlib.h>

int retornaMediana(int *vetor){

int tam=0;

    tam = sizeof(vetor);

    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 n = retornaMediana(&vetor);
int n2;

n2 = sizeof(vetor)/sizeof(int);

    printf("TAMANHO = %d\n\n",n);
    printf("TAMANHO = %d\n\n",n2);


}

How do I make the function return the actual vector size? I already passed by parameter, reference and nothing, I only receive that 4 as an answer.

    
asked by anonymous 26.03.2016 / 01:55

2 answers

2

This line is calculating the size correctly:

int len = sizeof(vetor)/sizeof(int);

It would be better

int len = sizeof(vetor)/sizeof(vetor[0]);

Because if you change the type of vetor , you will not be surprised by a that is difficult to see depending on the context.

It is important to understand that sizeof is already solved by the compiler because it simply knows what was done in the variable definition, so if you need to know the size of a vector passed by parameter, the remaining solution is always pass the vector and size.

Returning 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 size of the pointer:

tam = sizeof(vetor);

An output would be to calculate the size within the scope of the statement, 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 demo on IDEONE .

    
26.03.2016 / 14:33
0

The vector inside the method is now a pointer, so the size will always be 8 (if your file is 64x), to calculate its size, you must create a method that traverses the pointer and counts the positions. p>

int vec_len(int *vec){
    int c = -1;
    while(*(vec++))
        c++;
    return c;
}

I recommend that you use some value like 0 to identify when it reaches the end of the vector.

    
26.03.2016 / 04:35