Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 263
  • Last Modified:

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;

}

}

0
anshuma
Asked:
anshuma
1 Solution
 
limestarCommented:
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.
0
 
SalteCommented:
The double * a argument is modified but such a modification cannot afect the caller.

If the pointer a had been pointing to an array, then the get function could fill in that array. But this isn't what you are trying to do, you are trying to modify a itself and that doesn't work. Well, it works but when the function returns the modified value for a is lost.

void do_something()
{
   double * arr;
   int k;

   get(arr,k);
}

Problem here is that arr itself isn't changed. k is changed though since it is a reference argument.

Suggest you declare a also as reference argument:

void get(double * & a, int & n)
{
  ...code as before...
}

This should do the trick.

Alf

0
 
anshumaEngineeringAuthor Commented:
Thank you both.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now