I have the following code in C++:
typedef struct
{
int age;
int roomNumber;
} Student;
Student student;
student.age = 20;
student.roomNumber = 10;
vector<Student> studentV;
student.push_back(student);
student.push_back(student);
student.push_back(student);
Student student1[3];
int i;
for(vector<Student>::const_iterator iterator = studentV.begin();
iterator != studentV.end(); ++iterator,++i)
{
memcpy(&student1[i], iterator, sizeof(Student));
}
It show the following message for the memcpy part:
error: cannot convert 'std::vector<Student>::const_iterator {aka __gnu_cxx::__normal_iterator<const Student*, std::vector<Student> >}' to 'const void*' for argument '2' to 'void* memcpy(void*, const void*, size_t)'
What is the problem and how to fix it? is iterator can not be copied like this?
The second argument of memcpy
should be address of Student
object, so you should use &*iterator
instead of iterator
. Because of operator overloading those two are not equivalent.
But I would recommend not to use memcpy
at all.
What you want to do is copy what the iterator refers to. Use *iterator
to get the object referenced by the iterator and &
to get its address. By the way DO NOT use memcpy but the copy constructor:
student1[i] = *iterator;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With