5

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.

2
  • 2
    arr is a pointer, not an array. The syntax you use in the function declaration is just eye-candy for int sum(int *arr). You might like to read section 6 of the comp.lang.c FAQ.
    – pmg
    Apr 22, 2012 at 15:18
  • compile on/for a 64 bit machine you should see 8 as you are looking at the size of the pointer not the size of the array.
    – old_timer
    Apr 22, 2012 at 15:21

1 Answer 1

11

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).

9
  • If the question contains '4', post 'sizeof(pointer)' <g> Apr 22, 2012 at 15:14
  • How do I point to the array itself instead of the first element? Passing the length as a second argument is not a weakness a programmer should have to adapt to. Apr 22, 2012 at 23:10
  • 1
    If you have int arr[5];, then &arr gives you a pointer to an array of five int, int (*)[5]. The address is, however, the same as &arr[0], the address of the array's first element. What type of pointer you want depends on the situation. For summing the array elements, unless you want to have a different function for every size (int sum_5(int (*)[5]);, int sum_6(int (*)[6]);, you have to pass an int* and the number of elements. That's how C works. Apr 23, 2012 at 8:31
  • @Daniel @dissident I don't see why you can't just use sizeof(array) / sizeof(array[0]). It works for me. Sep 14, 2015 at 16:40
  • @B1KMusic In a scope where array refers to an actual array, that works. But in int sum(int arr[]), the name arr does not refer to an array, it refers to an int*. So if you compute sizeof arr / sizeof arr[0] in that function, you get sizeof(int*) / sizeof(int). Sep 14, 2015 at 16:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.