在指向对象的指针向量的for循环中的Segfault

use*_*616 1 c++ vector

我正在尝试编写一个程序来创建指向对象的指针向量,然后取消引用它以打印它所拥有的值.但由于seg故障,该程序正在中止.

分段故障cout << p1->rno << endl;display( )功能线上.

请帮我找出问题所在.

#include<iostream>
#include<vector>
using namespace std;
class student
{
  public:
  int rno;
  char name[25];
  student(int r,char *p):rno(r)
  {
     //cout << "Con No is" << ++cnt << endl;
     strcpy(name,p);
  }
  static int cnt;
};

void display(vector<student *> &vec)
{
     vector<student *> :: iterator p;
     student *p1;
     for(p = vec.begin( );p != vec.end( );++p);
     {
       p1 = *p;
       cout << p1->rno << endl;
     }
}
int student :: cnt = 0;

int main( )
{
    vector<student *> vec;
    student *p;
    int i = 0; 
    while(i < 10)
    {
      p = new student(i,"Ganesh");
      vec.push_back(p);
      i++;
    }
    display(vec);
    system("PAUSE 100");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

awe*_*oon 6

你弄错了

for(p = vec.begin( );p != vec.end( );++p);
//                                       ^
Run Code Online (Sandbox Code Playgroud)

你的for循环有空体.

PS我建议你打开警告,它可以帮助你避免这种错别字.例如,clang会抛出以下警告:

警告:for循环有空体[-Wempty-body]