Home > OS >  How to cast void* to vector<char *>?
How to cast void* to vector<char *>?

Time:06-13

There is a function which takes void*

After passing my vector<char*>, how do I cast it back to vector<char*> and print its content using casting in C ?

Example:

void testFunction(void* data){

   //cast data back to vector<char *> and print its content


}


int main()
{
   std::vector<char *> arg(1);
    std::string someString = "testString";
        arg[0] = (char *)someString.c_str();
        testFunction(&arg);
    return 0;
}

CodePudding user response:

Just use reinterpret_cast

vector<char*>* parg = reinterpret_cast<vector<char*>*>(data);
char* mystr = parg->at(0);

CodePudding user response:

You can use a static_cast to cast a void* pointer to almost any other type of pointer. The following code works for me:

void testFunction(void* data)
{
    std::vector<char*>* vecdata = static_cast<std::vector<char*>*>(data);
    for (auto c : *vecdata) std::cout << c;
    std::cout << std::endl;
}

CodePudding user response:

std::vector<char*>& myVec= *reinterpret_cast<std::vector<char*>*>(data);
std::cout<<myVec[0];

Well actually this worked.

  •  Tags:  
  • c
  • Related