Hello,
I am a complete noob in c++ and I am trying to work out this problem:
I need to get the user to input the number of elements of a dynamically allocated array and then return an average of the numbers.
I have tried to do the following:
#include <iostream>
using namespace std;
double avg(double r, int n);
int main()
{
int n;
cout << "Input the size of array:\t"; cin >> n;
double *r; r = new double[n];
for (int i=0;i<n;i++) {cout << "[" <<i<<"]:";cin >> r[i];}
cout << "Average is:\t"<< avg(r[n],n)<<endl;
delete[]r;
return 0;
}
double avg(double r, int n){
double sum = 0;
for (int i=0;i<n;i++){
sum = sum + *r[i]; // Error "subscript requires array or pointer type" given here
}
return (sum/n);
}
This, however, does not work and I get the error "subscript requires array or pointer type".
Pass the pointer itself to the function ( declare the function to take a pointer parameter )
Even if you declared the function parameter 'r' as a pointer *r[i] will give you an error ( because you wouldn't need the * )
I guess you need to read a bit about pointers: http://www.cplusplus.com/doc/tutorial/pointers/
Thanks for the reply,
I have tried doing something like that but still couldnt get it to work. I changed the function parameter to a pointer, but then, how do I actually pass the arguments into the function?