0

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.

4
  • Call it with DoesPeriodExist(it1);; The reference is already in the definition of the function argument,. Commented Jul 18, 2017 at 10:24
  • wSignal& specifies a reference type, not a pointer Commented Jul 18, 2017 at 10:24
  • A pointer to struct wSignal is wSignal *s. Commented Jul 18, 2017 at 10:24
  • Do you mean if(it1->MAC != "") in the function - or if(s->MAC != "")? Commented Jul 18, 2017 at 11:10

3 Answers 3

4

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.