文件I/O中的分段错误

Nee*_*hta 1 c++ file-io pointers fstream segmentation-fault

我编写了一个代码来读取文件,将其存储在一个结构中并显示它.但不知何故,它给了我一个分段错误,我不知道为什么.有人可以帮帮我吗?

输出:

file: /home/neel/map2.txt
file opened
Start Intersection
a->road: 4

a->roadId[0]: 1
a->lane[0][0]: 2
a->lane[0][1]: 2

a->roadId[1]: 2
a->lane[1][0]: 2
a->lane[1][1]: 2

a->roadId[2]: 3
Segmentation fault
Run Code Online (Sandbox Code Playgroud)

码:

#include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;

struct Intersection
{
  unsigned short road;
  long long int *roadId;
  short *lane[2];
};

int main(int argc, char** argv)
{
  std::ifstream file;
  cout<<"file: "<<argv[1]<<endl;
  file.open(argv[1], std::ios::in);
  cout<<"file opened"<<endl;

  while (!file.eof())
  {
    cout<<"Start Intersection"<<endl;
    Intersection *a = new Intersection;
    file>>a->road;
    a->roadId = new long long int[a->road];
    a->lane[0] = new short[a->road];
    a->lane[1] = new short[a->road];
    cout<<"a->road: "<<a->road<<endl;
    for (int i=0; i<a->road; i++)
    {
      file>>a->roadId[i];

      cout<<endl<<"a->roadId["<<i<<"]: "<<a->roadId[i]<<endl;
      file>>a->lane[i][0];
      cout<<"a->lane["<<i<<"][0]: "<<a->lane[i][0]<<endl;
      file>>a->lane[i][1];
      cout<<"a->lane["<<i<<"][1]: "<<a->lane[i][1]<<endl;
    }
    cout<<"Intersection inserted"<<endl;
    delete a;
  }
}
Run Code Online (Sandbox Code Playgroud)

文本文件:

4

1
2
2

2
2
2

3
2
2

4
2
2
Run Code Online (Sandbox Code Playgroud)

lou*_*ear 6

lane是一个包含2个元素的数组,但是当你在内环中i到达时2,你正在尝试打印a->lane[2][0],这是不存在的.