为对象分配内存时出错

时间:2019-03-25 10:04:58

标签: c++

我正在尝试为我的类Polynom创建一个构造函数,但是我没有做错什么。请帮忙 !

Monome.hpp

class Monome{
  int n; //degré du monome
  float a; // coeff du monome
public:

// Constructeur par valeur (défaut)
Monome(int=1 , float=0);

Polynome.hpp

#include "Monome.hpp"
class Polynome{
  int deg;
  Monome ** Poly;
public:
  Polynome(int);
};

构造函数定义:

Polynome::Polynome(int Deg){
*Poly= new Monome[Deg*10]; // I'm having bad access in this line !
cout << "ok";
this->deg=Deg;

    for(int i=0;i<deg;i++){
    Monome A(i,0);
    *(this->Poly[i]) = A;
}     
}

2 个答案:

答案 0 :(得分:2)

class Polynome{
  int deg;
  Monome ** Poly; -------> this is a double pointer, which means,  it is a pointer which store pointers
public:
  Polynome(int);
};
*Poly= new Monome[Deg*10]; // I'm having bad access in this line !

在上面的代码中,您基本上要尝试的是访问poly中存储的指针,而实际上并没有为poly提供givinig内存。因此,它崩溃了。

正确的顺序是:

1. Allocate memory to poly as poly = new Monome*[n]; // where n holds the number of Monome pointers you want.
2. for (size_t i=0; i<n; i++)
         poly[i] = new Monome;

答案 1 :(得分:0)

好,您访问错误,原因是您访问的字段确实引用了垃圾值。

代替呼叫

*Poly= new Monome[Deg*10]; // I'm having bad access in this line !

您应该写

Poly = new Monome*[Deg*10];