Link to home
Start Free TrialLog in
Avatar of Amit
AmitFlag for United States of America

asked on

can somebody tell me why this program throws the error - memory cannot be read.

If somebody finds the mistake, please tell me the reason also,so that I can learn the langauge.


void get(double * a, int &n)

{

cout<<"Enter: ";
cin>>n;

cout<<"________________________"<<endl;

 a=new double[n];

for (int i=0;i<n;i++)

{

cout<<"Enter item "<<i+1<<":";
cin>>a[i];

}


}



void main()

{

int i;

double *game;

get(game,i);

for(int j=0;j<i;j++)

{

cout<<game[j]+5<<endl;

}

}

Avatar of limestar
limestar

You send a double * as a parameter to the funktion, and then assign to it. The problem with this is that the parameter is local, and the changes you make to it are going to have no effect outside the get() method.

What you need to do is either send a pointer to a pointer, double **a and then use *a = new double[n]; instead of the current code. Another alternative is to send a reference to the pointer instead of only a pointer.
ASKER CERTIFIED SOLUTION
Avatar of Salte
Salte

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Amit

ASKER

Thank you both.