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.