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

时间:2013-04-13 16:03:28

标签: 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;
}

1 个答案:

答案 0 :(得分:6)

你弄错了

for(p = vec.begin( );p != vec.end( );++p);
//                                       ^

你的 for loop 有空身。

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

  

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