0

Here is my code. I am not sure why the number of elements in my array is 2. Can anyone explain this?

#include <stdio.h>
int calculate(int age[]);
int main()
{
    
    int result, age1[]= {23,17,18,22,27,35};

    result=calculate(age1);
    printf("%d\n", result);

    return 0;
}

int calculate(int age[])
{
    int sum=0;
    int size;
    size=sizeof(age)/sizeof(age[0]);
    printf("Size:%d\n", size);
    for(int i=0; i<size;i++)
    {
        sum+=age[i];

    }
    return sum;
}

I couldn't get the sum of all elements. It only adds the first 2 elements in the array.

kile
  • 141
  • 1
  • 7
  • 1
    `size=sizeof(age)/sizeof(age[0]);` This does not do what you think it does, see [Why does a C array decay to a pointer when passed with size](https://stackoverflow.com/questions/46628989/why-does-a-c-array-decay-to-a-pointer-when-passed-with-size), for example. You need to pass the size as a separate argument. – dxiv Nov 07 '20 at 03:06
  • When compiling look at all the warnings. Both `clang` and `gcc` warn you with -Wsizeof-array-argument – rajashekar Nov 07 '20 at 03:09
  • @dxiv how can fix this? Any tips? – kile Nov 07 '20 at 03:27
  • @kile "*You need to pass the size as a separate argument*". Change the function to `int calculate(int age[], int size)` and call it as `calculate(age1, sizeof(age1)/sizeof(age1[0]))`. – dxiv Nov 07 '20 at 03:30
  • @dxiv great idea! – kile Nov 07 '20 at 06:05

0 Answers0