Monday, November 16, 2009

Number of elements in an array in C

Take the following piece of code:
int main()
    int nums[] = {1,2,3,4,5};
    printf("Outside: %d\n",sizeof(nums) / sizeof(*nums));
    return 0;

int f(int nums[]) {
    printf("Inside: %d\n",sizeof(nums) / sizeof(*nums));

Here is the output of the above code:
Outside: 5
Inside: 1
As you can see from the above output, when the calculation is done in the scope where the array was initialized, the correct output is displayed; but when it is passed to a function, the calculation fails!
This is because the formal argument int nums[]  does not contain any information about the array whereas the declaration of the array in the main function contains an implicit size  (determined by the number of items in the value), so as long as you use the variable in the main function (ie where it was declared), the compiler knows the size of the array.

When you send the array as a parameter to the f function, there is no information about the size sent along, it's just a pointer to an array of unknown size. The f function could be called from anywhere, so the compiler can't use the information about the variable in the main function.
If you want to know the size of the array in the f function, you have to send that along with the array as another parameter.