Rik Smits
Rik Smits

Reputation: 63

C++ use pointer to struct in function

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

Answers (3)

songyuanyao
songyuanyao

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

hildensia
hildensia

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

Sergey Kalinichenko
Sergey Kalinichenko

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:

  • You can pass the struct itself, DoesPeriodExist(it1), or
  • You can accept a pointer, bool 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

Related Questions