开发者

C++ return double pointer from function.... what's wrong?

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;

}


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜