Passing a vector to a function as void pointer

Deadly 提交于 2019-12-08 02:47:08

问题


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.


回答1:


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

cb(static_cast<void*>(&a));



回答2:


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



回答3:


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

cb(a.data());


来源:https://stackoverflow.com/questions/14825274/passing-a-vector-to-a-function-as-void-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!