** your second method which I have shown below will not work**
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
longdouble average(longdouble n[])
{
longint num_of_terms=sizeof(n)/16;//problem here - see comment below
longdouble sum=0;
longint i;
for(i=0; i<num_of_terms; i++)sum+=n[i];
return sum/num_of_terms;
}
int main()
{
longdouble n[]={1,2,3,4,5,6,7};
cout<<average(n)<<endl;
}
It will not work because the parameter being passed to the function is
only a pointer to the array not the array itself - so sizeof(n) will only report
4 bytes or so (the size of a pointer).
So longint num_of_terms=sizeof(n)/16; will be 4 /16 = 0
so return sum/num_of_terms; will a whatever sum happens to be DIVIDED BY 0. In this case it is 0.0/0
Divide by zero is a fatal error - it either crashes the program or is this case
the system catches it and reports NAN
It's impossible to know the size of an array, unless it's been created in the stack, and then only from the function that created it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
void f2(int *);
void f(){
int v1[4];
//Ok. The size of v1 is known because it was created in the stack and we're
//inside the function that created it.
int size1=sizeof(v1)/sizeof(*v1);
int *v2=newint[4];
//Wrong. v2 was created in the heap, not in the stack.
int size2=sizeof(v2)/sizeof(*v2);
f2(v1);
}
void f2(int *array){
//Wrong. This function did not create v1, so it doesn't know how big it is.
//Furthermore, at this point it's impossible to know the size of array.
int size1=sizeof(array)/sizeof(*array);
}
The only way for other functions to know the size of an array is by passing a size parameter (e.g. void f(int *array,int size);).