Reputation: 391
I have a problem passing a pointer to a function. Here is the code.
#include <iostream>
using namespace std;
int age = 14;
int weight = 66;
int SetAge(int &rAge);
int SetWeight(int *pWeight);
int main()
{
int &rAge = age;
int *pWeight = &weight;
cout << "I am " << rAge << " years old." << endl;
cout << "And I am " << *pWeight << " kg." << endl;
cout << "Next year I will be " << SetAge(rAge) << " years old." << endl;
cout << "And after a big meal I will be " << SetWeight(*pWeight);
cout << " kg." << endl;
return 0;
}
int SetAge(int &rAge)
{
rAge++;
return rAge;
}
int SetWeight(int *pWeight)
{
*pWeight++;
return *pWeight;
}
My compiler outputs this:
|| C:\Users\Ivan\Desktop\Exercise01.cpp: In function 'int main()':
Exercise01.cpp|20 col 65 error| invalid conversion from 'int' to 'int*' [-fpermissive]
|| cout << "And after a big meal I will be " << SetWeight(*pWeight);
|| ^
Exercise01.cpp|9 col 5 error| initializing argument 1 of 'int SetWeight(int*)' [-fpermissive]
|| int SetWeight(int *pWeight);
|| ^
PS: In real life I wouldnt use this but I got into it and I wanna get it working this way.
Upvotes: 0
Views: 105
Reputation: 595
The * symbol can have two different meanings in C++. When used in a function header, they indicate that the variable being passed is a pointer. When used elsewhere in front of a pointer it indicates that to which the pointer is pointing. It seems you may have confused these.
Upvotes: 0
Reputation: 391
First I took your feedback and changed:
cout << "And after a big meal I will be " << SetWeight(*pWeight);
// to
cout << "And after a big meal I will be " << SetWeight(pWeight);
// But after that I changed also:
*pWeight++;
// to
*pWeight += 1;
Upvotes: 0
Reputation: 29725
You shouldn't dereference the pointer. It should be:
cout << "And after a big meal I will be " << SetWeight(pWeight);
Also, in SetWeight()
, you are incrementing the pointer instead of incrementing the value, it should be:
int SetWeight(int *pWeight)
{
(*pWeight)++;
return *pWeight;
}
Upvotes: 5
Reputation: 14791
int *pWeight = &weight;
This declares pWeight
as a pointer to an int
. SetWeight
actually takes a pointer to an int
, so you can just pass pWeight
straight in without any other qualifiers:
cout << "And after a big meal I will be " << SetWeight(pWeight);
Upvotes: 1