-1

As far as I know, the following code can be used to obtain the length (meaning how many items it contains) of an array (in this example, an integer array):

int arrayOfInt[] = { 10, 20, 30, 40, 50 };

int lenght = sizeof(arrayOfInt) / sizeof(int);

This gives "5" as output, which is correct. However, if i use the same code in a function, it does not work.

int getLenght(int intArray[])
{
    return sizeof(intArray) / sizeof(int);
}

lenght = getLenght(arrayOfInt);

Using the function above, i get "1" as output. Which is not correct. Why does this happen? Am i doing something wrong or is it not possible?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Ricko Z
  • 53
  • 1
  • 1
  • 6

1 Answers1

5

This is not possible. Arrays, when passed as function argument, decays to the pointer to the first element, so essentially, inside the function,all you have is a pointer to the first element of the array.

Moreover, sizeof operator works on the supplied variable type, it has no way of knowing the actual type before the transformation.

To elaborate,

 int getLenght(int intArray[])

and

 int getLenght(int *intArray)

are functionally and behaviorally same. It's not an array anymore.


Having said that, just a suggestion, a more robust way of getting the number of elements in an array would be

  int length = sizeof(arrayOfInt) / sizeof(arrayOfInt[0]);

This makes the expression independent of the hardcoded datatype, retaining the actual purpose.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261