1

I'm a little confused when I run the code below:

int Maxi(int A[])
{
    return sizeof(A)/sizeof(A[0]);
}

int main()
{
    int A[5] = {1,2,3,4,5};
    print("%d \n", Maxi(A));
    return 0;
}

And I just get the result 2. It seems that sizeof(A) turns out to be 8, which is the size of a pointer. I know this may not be a question worthy asking, but I must miss something and I just cannot figure it out right now.

But if I do this:

int main()
{
    int A[5] = {1,2,3,4,5};
    print("%d \n", sizeof(A)/sizeof(A[0]));
    return 0;
}

It's all right then, and I thought it is related to the passage of value between functions, but I'm confused.

Thanks!

ray6080
  • 813
  • 2
  • 8
  • 22

3 Answers3

1

The A array decays to a pointer once you pass it as a parameter to a function. Hence it's size gets computed to 8 (I'm guessing you're on a 64-bit system). sizeof(A[0]) is 4 (an int) therefore that's your 2.

The reason it 'works' inside main is that the compiler is able to compute the size directly from your static initialization above.

Community
  • 1
  • 1
dragosht
  • 3,177
  • 2
  • 20
  • 30
1

You can't pass an integer array to another function with array name.

int Maxi(int A[])

is equal to this

int Maxi(int *A) 

syntax.

So whenever you are passing an array to another function you should pass number of elements in that array also.

int Maxi(int A[], int elements)
//....
// call should be
print("%d \n", Maxi(A, elements));

else it treats array as a integer pointer, and it will return the size of the pointer.

Sathish
  • 3,512
  • 1
  • 12
  • 25
0

When you pass an array to a function, within the called function, Maxi in this case, the parameter declaration for Maxi as int A[] same as int *A

int Maxi(int A[])

is equivalent to:

int Maxi(int *A)

So, an array passed is seen as a pointer within the called function, and size of a pointer is of course not the size of the array within Maxi,so, the size has to passed explicitly as in:

int Maxi(int A[], int sz)
{
    return sz/sizeof(A[0]);
}

int main()
{
    int A[5] = {1,2,3,4,5};
    printf("%d \n", Maxi(A, sizeof(A)));
    return 0;
}

This will output 5, as desired

Dr. Debasish Jana
  • 6,653
  • 3
  • 24
  • 55