-2

This is the code for finding the average of numbers passed as array in the function but it is giving incorrect length of the array when. It is known that array is converted into pointer but is there any way to find array length in the function(other than main)

#include <stdio.h>
int sum(int ar[]){
    int avg=0;
    int size= sizeof(ar) / sizeof(ar[0]);
    printf("\nThe size of the array is: %d",size);
    for(int i=0;i<size;i++){
        avg+=ar[i];
        // print("\n%d",avg);
    }
    return avg;
}

int main(int argc, char const *argv[])
{
    int average;
    int array[5]={1,2,3,4,5};
    average=sum(array);
    printf("\nThe average of the values in the array is: %d",average);
    return 0;
}

The corresponding output that I am getting is:

Output

Arpit
  • 394
  • 1
  • 11
  • @JosephSible-ReinstateMonica yes u can say to some exent but it is not clear how to print the length in the function if we want – Arpit Dec 18 '20 at 07:36
  • 1) We don't like screenshots, use copy-paste 2) Most of us gets itchy on an "i" or "u", please fix your writing style asap. – peterh Dec 18 '20 at 11:22

1 Answers1

-1

You are passing array by reference ( C doesn't allow passing array by value ).

Hence the size of sizeof(ar) is nothing but the size of integer pointer.

I suggest pass the array size as separate argument.

--- EDIT -----

int sum(int ar[]){ is same as int sum(int *ar){

Vagish
  • 2,520
  • 19
  • 32
  • If I use the same formula of finding the size in the main function, then it is giving the correct size – Arpit Dec 18 '20 at 07:33