So for background, I've been messing around doing examples on my own trying to further my understanding of pointers. So far I think I've been progressing but I can't wrap my head around one concept. I think my train of thought, logic, or something is wrong but I don't understand why. I'll provide two examples of code below to illustrate what I'm talking about.
Example 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
void adjustMinWage(double *p_minWage);
int main(){
double minWage = 8.75;
adjustMinWage(&minWage); //were passing the address of minWage
cout << "The minimum wage has been adjusted to: $" << minWage;
return 0;
}
void adjustMinWage(double *p_minWage){ //creates a local pointer, p_minWage and assigns it the address from &minWage
cout << "What would you like to change the new minimum wage to? $";
cin >> *p_minWage; // The value at the address of p_minWage (the same address as &minWage) is adjusted to some user input.
}
|
I don't really have any questions on the above example, I think my comments explain the procedure, if they do not, please correct me. The example above to more so a reference for the example below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
void adjustMinWage(double &minWage); //what does this function take?
int main(){
double minWage = 8.75;
double *p_minWage = &minWage; //the address of minWage is pointed to by p_minWage
adjustMinWage(p_minWage);
/*why do I pass the value at p_minWage instead of the address? I.e. Why should it be *p_minWage instead of p_minWage?
since the & (address operator) is in the function prototype, I'm lead to believe that I should be passing an address
and passing a pointer makes sense to me because it's value is an address
*/
cout << "The minimum wage has been adjusted to: $" << minWage << endl;
return 0;
}
void adjustMinWage(double &minWage){
cout << "What would you like to change the new minimum wage to? $";
cin >> minWage;
}
|
I understand that the code in the second example fails to compile because the argument should be *p_minWage, but I don't understand why. Since the parameters of my prototype are (double &minWage), I'm lead to believe that I should be passing an address that contains a double. Pointers are assigned address that point to values, so passing the pointer or the address itself seems like the right idea to me. However, after trial and error, I should be using the deference operator * to pass the value being pointed to, but why is this?
In example 1 it was very clear what was happening. The prototype had a pointer, which to me makes it apparent that the argument being passed to the function had to have been an address. In example 2, a value is being passed to the function even though it's using the address of operator in the prototype. Why do we need to pass the value pointed to by the pointer instead of the pointer itself?