简体   繁体   中英

How to convert void* to std::vector<std::vector<std::string> >*?

The some part of my code is given below. Here m_out defined like: static_cast<std::vector<std::vector<std::string> >* m_out;

The problem is in the given line m_out->push_back(row); . I get the "Segmentation fault (core dumped)" and when I debug I found that the cause in the given line above. I assume that, this is due to the fact that for m_out does not allocate memory. If so, how can I allocate memory for given two dimensional vector ?

int some_space::database::callback(void* data, int argc, char** argv, char** col_name)
 {
     if(m_out != 0) {
         m_out->clear();
     }   
     m_out = static_cast<std::vector<std::vector<std::string> >*>(data);
     std::vector<std::string> row;
     for(int i = 0; i < argc; ++i){
         row.push_back(argv[i] ? argv[i] : "(NULL)");
     }
     m_out->push_back(row);
     return 0;
 }

Thanks All. I solved my problem. I changed code like this. Now m_out is a variable and not a pointer static_cast<std::vector<std::vector<std::string> > m_out; .

int some_space::database::callback(void* data, int argc, char** argv, char** col_name)
 {
    if(m_out.size() != 0) {
        m_out.clear();
    }   
    for( int i = 0; i < 6; i++ ) { 
        m_out.push_back(std::vector< std::string >());
     }   
     for(int i = 0; i < argc; ++i) {
         m_out[i].push_back(std::string( (char *)argv[i] ? argv[i] : "(NULL)"));
     }   
     return 0;
 }

And this works fine :)

With the cast you claim that data points to a vector. If that's not true this won't work.

You have to created a vector first and make sure a pointer to it will be passed as data (wherever that's coming from). For example it could look similar to this:

db.set_callback_data(new std::vector<std::vector<std::string> >);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM