Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - sizeof int array always returns 4 [duplicate]

Tags:

c

gcc

dev-c++

Possible Duplicate:
sizeof array of structs in C?
sizeof an array passed as function argument

Just trying to write a basic sum() function.

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

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

    return total;
}

l always equates to 4 (I know to eventually divide it by sizeof int)

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

like image 780
Dissident Rage Avatar asked Apr 22 '12 15:04

Dissident Rage


1 Answers

As function arguments, arrays decay to pointers to the element type, so sizeof arr is sizeof(elem*).

You have to pass the number of elements as an extra argument, there is no way to determine that from the pointer to the array's first element (which is what is actually passed in that situation).

like image 106
Daniel Fischer Avatar answered Oct 15 '22 12:10

Daniel Fischer