Error in vector calculation in C

0

I am refactoring my code to make it more dynamic, but by including the line int n = sizeof(vetor)/sizeof(int); within the function bubble it no longer works correctly. Where am I going wrong?

Modified Code

void bubble(int vetor[])
{
    int n = sizeof(vetor)/sizeof(int);
    int k = n;
    int aux;

    for(int i=0; i<n; i++)
    {
        for(int j=0; j<k; j++)
        {
            if(vetor[j]>vetor[j+1])
            {
                aux=vetor[j];
                vetor[j]=vetor[j+1];
                vetor[j+1]=aux;
            }
        }
        k--;
    }
}

int main()
{
    int vetor[]={10,3,5,8,1,9,2,4,7,0,6,-1};
    int n=sizeof(vetor)/sizeof(int);

    bubble(vetor);

    printf("\n\n\n");

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

    printf("\n\n\n");

    system("pause");
    return 0;
}

Original Code

void bubble(int vetor[],int n)
{
    int k = n;
    int aux;

    for(int i=0; i<n; i++)
    {
        for(int j=0; j<k; j++)
        {
            if(vetor[j]>vetor[j+1])
            {
                aux=vetor[j];
                vetor[j]=vetor[j+1];
                vetor[j+1]=aux;
            }
        }
        k--;
    }
}

int main()
{
    int vetor[]={10,3,5,8,1,9,2,4,7,0,6,-1};
    int n=sizeof(vetor)/sizeof(int);

    bubble(vetor,n);

    printf("\n\n\n");

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

    printf("\n\n\n");

    system("pause");
    return 0;
}
    
asked by anonymous 25.02.2018 / 20:30

1 answer

3

Because when you use a vector as a parameter in a function, in this case the compiler interprets as a pointer. In other words:

void bubble(int vetor[])

It's the equivalent of this:

void bubble(int *vetor)

And then the sizeof(vetor) becomes sizeof(int *) and will give you 8, regardless of how many elements there are in the vector.

The reason for this is that sizeof is resolved at compile time, and corresponds to the amount of bytes in memory that will be allocated to store the contents of a variable. It is not determined at runtime. In the case of the original code, the compiler can easily figure out how much memory it will need to allocate vetor . In the case of the modified code, the only thing it will allocate is a pointer, and then the code will go wrong.

The solution to this is to revert to what was used in the original code. Do not rely on sizeof for strings, arrays, or linked lists, as often it will not do what you would have thought it would.

Here's a test to prove it:

int xxx(int vetor[]) {
    return sizeof(vetor);
}

int main() {
    int vetor[] = {10, 3, 5, 8, 1, 9, 2, 4, 7, 0, 6, -1};
    int n = sizeof(vetor) / sizeof(int);
    printf("%d\n", n);
    printf("%d\n", xxx(vetor));
}

Here's the output:

12
8

See here that running on ideone.

    
25.02.2018 / 21:38