【问题标题】:Segmentation Fault (Core Dumped) After reading from file从文件读取后分段错误(核心转储)
【发布时间】:2016-02-25 20:15:19
【问题描述】:

我正在尝试读取一个看起来像这样的.txt 文件...

Rhombus 118.5 112.4 69.9

然后,我尝试使用参数或值 118.5112.469.9 初始化 Shapes 类的构造函数。但是,我收到 Segmentation Fault (Core Dumped) 错误 - 我知道它来自我的代码中的哪一行。就是不知道怎么解决...

我的代码在下面...

istream& inputpoints(istream &is, Shapes * & shape)
{
   string name;
   double x, y, z;
   if (is >> name) {
       if (is >> x >> y >> z) {
           *shape = Shapes(x, y, z); // Segementation fault (core dump) happening here
       }
   }
   return is;
}

我相信是*shape = Shapes(x, y, z) 行导致了所有这些问题。如果我没有将* 放在shape 之前,则会收到Shapes 无法分配给Shapes* 错误。

如果有人可以在这里帮助我,将不胜感激。

谢谢

【问题讨论】:

    标签: c++ segmentation-fault iostream istream


    【解决方案1】:

    几个问题。首先,您将指向临时(堆栈)对象的指针分配给输出参数。

    为了更好的样式和可读性,声明你的函数,使第二个参数是一个指向 ppShapes 的指针。

    istream& inputpoints(istream &is, Shapes** ppShapes)
    {
    

    要解决主要问题,请更改此行:

    *shape = Shapes(x, y, z); // Segementation fault (core dump) happening here
    

    变成这样:

    *ppShapes = new Shapes(x, y, z);
    

    如下调用输入点:

    Shapes* pShapes = NULL;
    
    istream = inputpoints(istream, &pShapes);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-12
      • 2018-12-09
      • 2012-11-04
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多