将结构的Vector传递给带有void *的函数,如参数中所示

时间:2018-05-02 08:02:47

标签: c++ vector stl

继续我的上一个问题我面临的另一个问题是将结构向量传递给带有void *的函数,如参数

    SELECT
        t1.id
       ,t1.name
       ,t1.reg_no
       ,t1.zone
       ,t1.college
       ,t2.center
       ,t3.sub_code
    FROM db_exam t1
    INNER JOIN db_exam t2
    ON t2.id=t1.id
    AND t2.center='AB'
    INNER JOIN db_exam t3
    ON t3.id=t1.id
    AND t3.sub_code=2;

我收到空指针错误

1 个答案:

答案 0 :(得分:0)

您的代码存在多个问题,例如您没有分配内存,其次它本身就是迭代器/指针,因此您需要更改代码,如下所示:

  #include <iostream>
  #include <vector>
  #include <memory>
  struct MMT
  {
     int a;
     char b;
     int * data;
  };
  int func(void *structPtr){
     //use the structure member
  }
  int main ()
  {
      //Better to use smart pointers so no need to manage memory
      std::vector<std::unique_ptr<MMT>> myvector;


      for (int i=1; i<=5; i++){

           myvector.push_back(std::unique_ptr<MMT>(new MMT{i,'a'}));
      }
      std::cout << "myvector contains:";
      for (std::vector<std::unique_ptr<MMT>>::iterator it = myvector.begin() ; it !=myvector.end(); ++it)
      {
        func((void*)(it->get()));
      }
      std::cout << '\n';
      return 0;
  }