Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;

}
like image 771
user69514 Avatar asked Mar 20 '10 19:03

user69514


People also ask

How do I return multiple pointers from a function?

We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function, we will use two variables to store the results, and the function will take pointer type data. So we have to pass the address of the data.

Is returning a function pointer possible in C?

Pointers in C programming language is a variable which is used to store the memory address of another variable. We can pass pointers to the function as well as return pointer from a function.

Can you have a double pointer in C?

In the C programming language double pointer behave similarly to a normal pointer in C. So, the size of the double-pointer variable and the size of the normal pointer variable is always equal.

What is a reason for using double pointers int * *?

Double pointers can also be used when we want to alter or change the value of the pointer. In general double pointers are used if we want to store or reserve the memory allocation or assignment even outside of a function call we can do it using double pointer by just passing these functions with ** arg.


1 Answers

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;
}
like image 189
JaredPar Avatar answered Sep 22 '22 03:09

JaredPar