0

i have simple main that called simple methods with array as parameter
the size in the array is right , but then when i try to print the array im getting different sizeof array :

int bubbleSort(int arr[]) // yeah i know this sort is not complete 
{
    int arrSize = sizeof(arr); // HERE IS SIZE IS 4 
    bool bSorted = true;
    while(bSorted)
    {
        for(int i=0;i<arrSize;i++)
        {

            if(arr[i]>arr[i+1])
            {
                int tmp =  arr[i];
                arr[i] = arr[i+1];
                arr[i+1] = tmp;
            }


        }
        bSorted = false;
    }

    return 1;
}


int  main(int argc, char* argv[])
{


    int arr[] = {4,3,7,8,9};
    bubbleSort(arr);
    int sOf = sizeof(arr); // HERE THE SIZE IS 20 ????
    for(int j=0;j < sOf ;j++)
    {
        printf("%d",arr[j]);
    }
    return 0;
}
user63898
  • 29,839
  • 85
  • 272
  • 514

2 Answers2

4

You cannot pass arrays* by value as function parameters (nor return them in such fashion). The syntax void f(int a[]) is merely syntactic sugar that is in every aspect identical to void f(int * a), and the function parameter is a pointer, not an array. So you end up measuring the size of the pointer.

The alternative syntax may serve as a loose kind of documentation of intent, signalling that you plan to call this function with the address of an array element, but there is no actual difference to the pointer syntax.

*) Array types and function types are both constrained thus, which is why people often say that they are not first-class citizens of the type system.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

Due to the language being stupid, this:

int bubbleSort(int arr[])

actually means this:

int bubbleSort(int* arr)

So sizeof(arr) is the size of a pointer.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055