Reputation: 63
I am trying to us a pointer to a struct in C++. I have struct wSignal with member MAC. I give the pointer of a struct to the function.
Definition struct:
struct wSignal
{
std::string MAC;
};
using the function:
wSignal it1 = {"22:44:66:AA:BB:CC"};
DoesPeriodExist(&it1);
definition of the function:
bool DoesPeriodExist (wSignal& s)
{
if(it1->MAC != "")
}
Error I get:
error: base operand of ‘->’ has non-pointer type ‘wSignal’
What am I doing wrong? How can I use the pointer? Sorry if this is a silly questions. I am not very familiar with pointers and am trying the understand the concept.
Upvotes: 0
Views: 121
Reputation: 172884
You're declaring the parameter as a reference (to wSignal
), not a pointer, for this case you should change the function to
bool DoesPeriodExist (wSignal& s)
{
if(s.MAC != "") ...
}
and pass the argument like
wSignal it1 = {"22:44:66:AA:BB:CC"};
DoesPeriodExist(it1);
If you want to go with pointer, then the parameter type should be changed to the pointer (to wSignal
)
bool DoesPeriodExist (wSignal* s)
{
if(s->MAC != "")
}
and pass the argument like your code showed
wSignal it1 = {"22:44:66:AA:BB:CC"};
DoesPeriodExist(&it1);
Upvotes: 4
Reputation: 1740
Your definition of DoesPeriodExist()
does not expect a pointer but a reference to a wSignal
. The correct signature would be
bool DoesPeriodExist(wSignal* s)
Thus the base operand in your implementation is not a pointer but a reference, which is used with the .
operator.
Upvotes: 0
Reputation: 726479
You are giving a pointer to struct
to a function that expects a reference to a struct
.
This is a mismatch that needs to be fixed:
struct
itself, DoesPeriodExist(it1)
, orbool DoesPeriodExist (wSignal* s)
The first approach is preferable in situations when wSignal
must be non-null. If you wish to allow passing NULL
to DoesPeriodExist
, only the second approach will work, because NULL
references are not allowed.
Upvotes: 1