I have a callback function that takes a void *
as a parameter to pass arguments to and I'd like to pass a vector to the function. The function will be called multiple times so after the callback process is complete, I'd like to be able to iterate over all the elements that have been push_back()
'ed through the callback.
static void cb(void *data)
{
vector<int> *p = static_cast<vector<int>*>(data); //Attempting to convert *void to vector<int>
p->push_back(1);
}
int main()
{
vector<int> a(10); //Max of 10 push_back()s? vector<int> a; gives memory error.
cb((void*)&a.at(0));
cout << a.at(0); //Gives a random number of 6 digits or higher
}
The issue is that it does not properly have a value of "1" when a.at(0)
is called after the callback, just some random number.
As this is C, you cannot pass the pointer by reference without passing in a pointer to the pointer (e.g., void ** rather than void * to point to the pointer). You need to return the new pointer. What is happening: f(a1);
When we pass an array to a function, a pointer is actually passed. However, to pass a vector there are two ways to do so: Pass By value. Pass By Reference.
In the case of passing a vector as a parameter in any function of C++, the things are not different. We can pass a vector either by value or by reference.
After declaration, we store the address of variable 'data' in a void pointer variable, i.e., ptr. Now, we want to assign the void pointer to integer pointer, in order to do this, we need to apply the cast operator, i.e., (int *) to the void pointer variable.
Assuming that you cannot change the signature of cb()
, try this:
cb(static_cast<void*>(&a));
Here:
cb ((void*)&a.at(0));
you pass a pointer to the first element of the vector, not the vector itself, but here:
vector <int> *p = static_cast <vector <int> *> (data);
you cast passed data to the pointer to a vector, which is probably undefined behavior. If you want to pass pointer to the whole vector, pass like this:
cb ((void *)&a);
If you really want to pass a pointer to an element of the vector, then you should cast like this:
int * = static_cast <int *> (data);
In C++11, you have vector::data
:
cb(a.data());
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