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;
}
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.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With