views:

207

answers:

1

I can't seem to figure out what's wrong with my function.... I need to ask the user for a price and then return it as a double pointer, but I get tons and tons of errors:

double* getPrice()

{

    double* price;

    cout << "Enter Price of CD: " << endl;

    cin >> &price;



    return price;

}
+9  A: 

In order to use a pointer of any kind it needs to point to valid memory. Right now you have a pointer which is uninitialized and points to garbage. Try the following

double* price = new double();

Additionally you need to have cin pass to a double not a double**.

cin >> *price;

Note this will allocate new memory in your process which must be freed at a later time. Namely by the caller of getPrice. For example

double* p = getPrice();
...
delete p;

Ideally in this scenario you shouldn't be allocated a pointer at all because it introduces unnecessary memory management overhead. A much easier implementation would be the following

double getPrice() {
  double price;
  cout << "Enter Price of CD: " << endl;
  cin >> price;
  return price;
}
JaredPar
great... i get it now. thanks