Function that counts number of vector elements

Asked

Viewed 7,041 times

0

I tried to use this function to count the number of vector elements, but it doesn’t work.

int tamanho(int *p) {

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

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

It has already worked:

 for(int i=0; i<sizeof(vetor) / sizeof(int ); i++) {
        //printf("%d", vetor[i]);
   }

1 answer

1


The second code in for appears to be a "vector" in fact. And its total size must be known.

The first code in the function is just a pointer. It has its known size, i.e., it is the size of the pointed object. He doesn’t understand that it’s a sequence and it has other elements and he needs to know the total size allocated to all of them. This information should be controlled by the programmer.

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

The solution is to keep passing the total size of the allocation of these pointers or the number of elements you should consider as existing everywhere you need. Without that information, there’s no telling where 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 get to it. Which is what happens with strings. But it’s slow, not recommended. string is one of the biggest mistakes of C.

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

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

I put in the Github for future reference.

But please don’t do it, it doesn’t pay. Macros are not hygienic, if you pass something wrong for this, it will give problem, and expect it to be serious and noticeable, otherwise you will have a bug hard to find.

Browser other questions tagged

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