How to return vector size with sizeof ()?

7

This is the code I'm using, but the return of the tamVet function is not the size of the vector, but the size of the pointer over itself.

#include <stdio.h>

int tamVet(int *vet){
    int tam;
    tam = sizeof(vet) / sizeof(vet[0]);
    return tam; //Está retornando 1 invés de 10, o número de elementos de vetor[10]
}

int main(){
    int vetor[10];
    printf("%i", tamVetor(vetor));
    return 0;
}
    
asked by anonymous 17.09.2014 / 23:10

1 answer

11

In C, as soon as you pass an array to a function the array "decays" to a pointer to its first element. The length of the vector is forgotten and the only way to pass it to function is by using a separate argument. For example, main gets an argument argc in addition to the argv .

In your case, if the only thing you want to do is create something to have to type less I think you can solve it using macros instead of functions.

#define TAMVET(vet) (sizeof(vet)/sizeof((vet)[0]))
    
17.09.2014 / 23:20