Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a vector to a function as void pointer

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.

like image 289
user99545 Avatar asked Feb 12 '13 04:02

user99545


People also ask

Can I pass void pointer to function?

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);

How do you pass a vector pointer?

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.

Can you pass a vector 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.

How do you assign a void pointer?

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.


3 Answers

Assuming that you cannot change the signature of cb(), try this:

cb(static_cast<void*>(&a));
like image 84
Robᵩ Avatar answered Oct 10 '22 23:10

Robᵩ


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);
like image 4
Mikhail Vladimirov Avatar answered Oct 11 '22 00:10

Mikhail Vladimirov


In C++11, you have vector::data:

cb(a.data());
like image 3
Walter Avatar answered Oct 10 '22 23:10

Walter