c++arrayssizesizeof

Using sizeof on arrays passed as parameters


Possible Duplicate:
Sizeof array passed as parameter

Given the function below I understand that sizeof returns the size of the pointer of the type in the array.

int myFunc(char my_array[5])
{
    return sizeof(my_array);
}

However calling sizeof on an array not passed as a parameter normally returns the sizeof the array.

What causes this inconsistency? What is the best way of getting the size of an array when it is passed as a parameter?


Solution

  • What causes this inconsistency?

    The name of the array decays as an pointer to its first element.
    When you pass an array to an function, this decaying takes place and hence the expression passed to sizeof is a pointer thus returning pointer size.

    However, an array passed to sizeof always returns size of the array because there is no decaying to an pointer in this case.

    What is the best way of getting the size of an array when it is passed as a parameter?

    Don't pass them by value, pass them by reference or
    Pass size as an separate argument to the function.