How to return vector size with sizeof()?

Asked

Viewed 16,087 times

7

This is the code I’m using, but the return of the tamVet function is not the vector size, but the pointer size on 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;
}
  • 2

    "How to return vector size" I find an interesting question. But in your case, pq makes sure it’s with sizeof()?

  • I don’t know any other way to get vector size

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 the function is by using a separate argument. For example, the main gets an argument argc beyond the vector 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 using macros instead of functions.

#define TAMVET(vet) (sizeof(vet)/sizeof((vet)[0]))
  • Got it. I didn’t know this hugomg shape, thank you

  • Tome quite a lot Watch out for macros. It’s extremely easy to shoot yourself in the foot with them.

  • Right, I’m studying about them now :)

Browser other questions tagged

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