Passing an object pointed to by an iterator by reference to a function C++

904 Views Asked by At

I though that I understood iterators and addressing etc. but obviously not. See my below code below which is purely an example.

I need to be able to pass by pointer or reference each structure of mystructs to MyFunc(). The function should be able to update the actual structure that is passed, and not by copy or value.

I receive the compiler error :

error: cannot convert 'MY_STRUCT' to 'MY_STRUCT*' for argument '1' to 'void MyFunc(MY_STRUCT*)'

If I just pass the iterator address, this also doesn't work.

What is the correct way to do this. Thanks in advance.

typedef struct
{
   int var1;
   int var2;
   std::string name;

}MY_STRUCT;

std::list<MY_STRUCT> mystructs;

void MyFunc(MY_STRUCT*)
{
    // Do something
}


// populate the list with structs etc.. not included here
//.....


for (std::list<MY_STRUCT>::iterator it = mystructs.begin();it != mystructs.end(); ++it)
{
     MyFunc(*it);
}
2

There are 2 best solutions below

0
On

Your function requires a pointer, use & to get the address of something.

MyFunc(&*it);

*it returns a reference to the MY_STRUCT object, you need to use & to convert that reference to a pointer. This is normal, the fact that you are using iterators makes no difference at all.

The alternative (maybe better in C++) would be to convert your MyFunc function to take a reference instead of a pointer.

2
On

Passing by reference in C++ is done with:

void MyFunc(MY_STRUCT&)
{
    // Do something
}

So your call would be correct, what you currently want is to pass the pointer, which you can do with dereferencing the dereferenced iterator (by passing the address of the dereferenced object):

void MyFunc(MY_STRUCT*)
{
    // Do something
}


// populate the list with structs etc.. not included here
//.....
int main() {

    for (std::list<MY_STRUCT>::iterator it = mystructs.begin();it != mystructs.begin(); ++it)
    {
         MyFunc(&*it);
    }
}