0

I have tried to use function to calculate the sum of elements in array. Logic is correct but I think there is some syntax error but I am not getting it. Please help me in solving this.

#include <stdio.h>
int add(int arr[]);

int main(void)
{
    int nums[] = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512 };
    int result = add(nums);
    printf("Result: %d\n", result);
    return 0;
}

int add(int arr[])
{
    int total = 0;
    int i;
    for (i = 0; i < sizeof(arr)/sizeof(arr[0]); i++) {
        total += arr[i];
    }
    return total;
}

The error I am facing is this ->
main.c:16:27: warning: ‘sizeof’ on array function parameter ‘arr’ will return size of ‘int *’ [-Wsizeof-array-argument] for (i = 0; i < sizeof(arr)/sizeof(arr[0]); i++) { ^ main.c:12:13: note: declared here int add(int arr[]) ^~~ Result: 3

Code With Faraz
  • 62
  • 2
  • 12
  • What error do you get? – Davo Sep 01 '21 at 17:39
  • 2
    `sizeof(arr)` worked on a function argument does not get the size of the array, but the size of the pointer that it decays to. – Weather Vane Sep 01 '21 at 17:40
  • main.c:16:27: warning: ‘sizeof’ on array function parameter ‘arr’ will return size of ‘int *’ [-Wsizeof-array-argument] for (i = 0; i < sizeof(arr)/sizeof(arr[0]); i++) { ^ main.c:12:13: note: declared here int add(int arr[]) ^~~ Result: 3 – Code With Faraz Sep 01 '21 at 17:40
  • @WeatherVane then how to get the size of an array in the add() function? – Code With Faraz Sep 01 '21 at 17:42
  • 1
    You must pass the number of elements as another function argument (or use a sentinel value). Your computation would have worked if done on the array itself in `main` as shown in the dup. – Weather Vane Sep 01 '21 at 17:42
  • @CodeWithFaraz Edit error text into your that into your question. (it'll preserve the newline, unlike comments) – Alexander Sep 01 '21 at 17:42
  • Pass the 10 as extra parameter. BTW 2**10 - 1. – Joop Eggen Sep 01 '21 at 17:43
  • And this is why C blows my mind. Why don't they just package the array size as part of the array? Everyone is going to be hand-rolling that the same way, for themselves – Alexander Sep 01 '21 at 17:43
  • 1
    @Alexander One of the designers of C called zero terminated strings the greatest error. Also an array problem. Pascal solved it better. – Joop Eggen Sep 01 '21 at 17:46
  • 1
    @Alexander C has no packaging for strings either, which rely on a sentinel NUL marker. – Weather Vane Sep 01 '21 at 17:46
  • @WeatherVane At least they have that, and don't rely on you mindlessly passing the string size around everywhere (though you still do need to do that, if you're going to be writing into the string) – Alexander Sep 01 '21 at 17:46
  • @Alexander the array argument `*argv[]` passed to `main` uses both the number of elements as a separate argument `argc` *and* a sentinel value, in this case the `NULL` pointer. – Weather Vane Sep 01 '21 at 17:48
  • guys, stay focused :P – Davo Sep 01 '21 at 17:51

0 Answers0