0

I am trying to sum the elements of an int array, without having prior knowledge of the the array length.

#include <stdio.h>

int sum(int anArray[]) {
  
  int sum = 0;
  size_t arrayLength = sizeof(anArray) / sizeof(int);
  
  for(int i = 0; i < arrayLength; i++) {
    sum += anArray[i];
  }

  return sum;
}

int main() {
  int myIntegers[3] = {1, 2, 3};

  printf("sum: %d", sum(myIntegers));
  return 0;
}

I get 3 as a result, but I expect 6. I don't understand why this happens.

More particularly

sizeof(anArray)

the above returns 8 for a 3 element array, while I expect it to return 12. Note that sizeof(int) in my machine is 4.

Edit: I did some digging, and this is the answer to my question.

Svaris
  • 11
  • 3
  • If you have no knowledge of the array length (which, in this case, you indeed do not), then it is quite impossible to sum the elements of the array or indeed to do much of anything with them. – Steve Summit Sep 13 '22 at 21:32
  • 1
    Your function `sum` does *not* receive an array, so it has no way (using `sizeof` or otherwise) to find the size of the array. Your function receives a pointer to the array's first element, so `sizeof(anArray)` is always going to give you the size of that pointer, which is `sizeof(int *)`, which will probably be 4 or 8 on an ordinary machine today. (And you say you saw 8, so that's that.) – Steve Summit Sep 13 '22 at 21:35
  • See the [second answer](https://stackoverflow.com/questions/37538#10349610) at the [duplicate question](https://stackoverflow.com/questions/37538) for more information. – Steve Summit Sep 13 '22 at 21:42
  • What about a sentinel value? If you don't want to pass the size you could indicate the length using the data (assuming there is a data value that can never come up...) https://onlinegdb.com/HeUsAP_E6 – Jerry Jeremiah Sep 13 '22 at 21:52
  • The other thing you could do is encode the size into the type itself. sizeof can be used on an array in a struct: https://onlinegdb.com/DXEUiAbOx – Jerry Jeremiah Sep 13 '22 at 21:58
  • It sounds like, on your machine, `sizeof(int *)` is probably 8, and `sizeof(int)` is, as you say, 4. 8/4 is 2, so your loop runs twice, computing the sum of the first two elements of the array, 1 + 2 = 3. – Steve Summit Sep 15 '22 at 16:44
  • Your program cannot work as written. See the [second answer](https://stackoverflow.com/questions/37538#10349610) at the [duplicate question](https://stackoverflow.com/questions/37538) for more information. – Steve Summit Sep 15 '22 at 16:45

0 Answers0