Function that counts number of vector elements [duplicate]

1

I tried to use this function to count the number of vector elements, but it does not work.

int tamanho(int *p) {

    return sizeof(p) / sizeof(int*);
}

I wanted to pass for : i< tamanho(vetor) .

That's how it worked:

 for(int i=0; i<sizeof(vetor) / sizeof(int ); i++) {
        //printf("%d", vetor[i]);
   }
    
asked by anonymous 03.10.2016 / 14:49

1 answer

1

The second in for seems to be a "vector" in fact. And its full size should be known.

The first one in the function is just a pointer. It has its known size, that is, it is the size of the pointed object. He does not understand that it is a sequence and has other elements and needs to know the total size allocated to all of them. This information should be controlled by the programmer.

There is a myth that arrays and pointers are the same . They are not, and this is one of the main points.

The solution is to get past the total allocation size of these pointers or the number of elements that you should consider as existing everywhere you need it. Without this information, there is no way to know how far to go.

What some programmers often do is create an abstraction to deal with it. It can be something as simple as a structure with the size and pointer to the first element, or a complex type full of features.

Another possibility is to have a terminator and count the items until you reach it. Which is what happens with strings . But it is slow, not commendable. string is one of the biggest C errors.

If that really is an array and not a pointer and has its size known and just wants to encapsulate the sizeof(vetor) / sizeof(int) formula in a function, there are those who create a macro to solve this, solution nut. It would look something like this:

#define tamanho(vetor) (sizeof((vetor)) / sizeof(int))

But please do not do this, it does not pay. Macros are not hygienic, if something goes wrong for that, it will give you a problem, and expect it to be serious and noticeable, otherwise you will have a difficult bug .     

03.10.2016 / 15:16