Confusion in access to vector size in C bytes

Asked

Viewed 39 times

2

In the code below:

#include <stdio.h>

void testaTamanhoVetor(int vetor[])
{
    printf("tamanho do vetor em bytes na funcao: %zu", sizeof(vetor));
}

int main()
{
    int a[10];
    printf("tamanho do vetor em bytes no main: %zu\n", sizeof(a));
    testaTamanhoVetor(a);
    return 0;
}

The exit will be

tamanho do vetor em bytes no main: 40

tamanho do vetor em bytes na funcao: 8

Why are sizes different? I just wanted to access the actual vector size in the function.

1 answer

3


You don’t pass arrays for a function, just pass pointers. The syntax is a bit misleading looking like you’re using a array but it is a pointer. There it is the same as writing:

void testaTamanhoVetor(int *vetor)

And a 64-bit pointer on architecture has 8 bytes, so it’s the size you got, not the vector size. Only the unit being compiled at that time of the array You know your size, the programmer should control this for every application.

Even if you do the below you will not have the information because they are two completely different objects, one of them is a vector of other objects and the other is a pointer to an object. In one you’re taking a box with something inside and in another you’re taking an envelope with a text inside that says where there’s a box with objects inside, obviously the envelope and the box have different sizes.

void testaTamanhoVetor(int vetor[10])

You have to pass the size together to have this information. You can do this with an extra parameter or you can create a struct that keeps the two things together in an abstract way, which is the most correct way, or at least modern, for most situations, but a little more advanced. Simplest:

void testaTamanhoVetor(int vetor[], int tamanho)

And of course, you’ll have to pass the size from where the array was created.

See more in Arrays are pointers?.

  • How confusing this language is... But I get it, thank you very much!!

  • 3

    It’s not, and the ones with the clearest rules, but people "learn" without studying it first, so it gets complicated. And is the most powerful and flexible as well as efficient.

Browser other questions tagged

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