I am having difficulties passing dynamically allocated array to the function by reference. "The array should be transmitted to the function by reference". My program should take n amount of integers and find out the minimum. That minimum should be added to all the arrays that the user has entered. But the BY REFERENCE part kills me. I tried (int &x[],int &n) but failed. PLease help, thank you very much.
void add_min(int x[], int n) { int add[n]; int mini = x[0]; int i; for(i = 0; i < n; i++) { if(x[i] < mini) { mini = x[i]; } } for(i = 0; i < n; i++) { add[i] = x[i] + mini; } for(i = 0; i< n ; i++) { cout<<add[i]<<endl; } } int main() { int *x; int n; cout<<"Enter the amount of integers"<<endl; cin>>n; x = new int[n]; cout<<"Enter the integers"<<endl; for(unsigned i = 0; i < n; i++) { cin>>x[i]; } add_min(x,n); delete x; return 0; }
std::vectorinstead of arrays B) this is homework and you are not allowed to usestd::vector, in that case...well... you should usestd::vectorvoid add_min(int (&x)[10], int n). You should use a reference to a pointervoid add_min(int *&x, int n).&x[0]orx, since they mean the same thing. I'm not 100% sure however.delete[]when you use arraynew!