C - sizeof int array always returns 4

Possible duplicate:
sizeof arrays in C?
sizeof the array passed as an argument to the function

Just try to write a basic function sum().

int sum(int arr[]) {
    int total = 0 , i = 0 , l = sizeof arr;

    for(i=0;i<l;i++) {
        total += arr[i];
    }

    return total;
}

lalways equal to 4 (I know that in the end we will divide it by sizeof int)

Running Dev-C ++ with default compiler settings in Windows 7.

+5
source share
1 answer

Arrays are decomposed into pointers to the type of the element as arguments to the function, therefore sizeof arr- sizeof(elem*).

You must pass the number of elements as an additional argument, there is no way to determine this from a pointer to the first element of the array (which is actually passed in this situation).

+11

All Articles