使用C ++中的指针访问和操作数组

时间:2015-10-10 17:03:02

标签: c++ arrays pointers

我试图在我的c ++类中使用指针访问数组。

下面是我的班级。

#include <iostream>
using namespace std;

class Poly
{
    friend istream &operator>>(istream &, Poly &);
    friend ostream &operator<<(ostream &, const Poly &);

public:
    Poly();
    Poly(int);
    Poly(int, int);
    Poly(const Poly &);
    ~Poly();

    int getCoeff(int) const;
    int getMaxPow() const;
    void setCoeff(int, int);
    void setMaxPow(int);

    Poly operator+(const Poly &) const;
    Poly operator+=(const Poly &);

    Poly operator-(const Poly &) const;
    Poly operator-=(const Poly &);

    Poly operator*(const Poly &) const;
    Poly operator*=(const Poly &);

    Poly operator=(const Poly &);

    bool operator==(const Poly &) const;
    bool operator!=(const Poly &) const;

private:
    int* coeffPtr;
    int maxPow;
};
下面的

是我的构造函数

#include "poly.h"
#include <iostream>
using namespace std;

Poly::Poly() {
    maxPow = 0;
    int eq[1];
    coeffPtr = &eq[0];
    *coeffPtr = 0;
}

Poly::Poly(int coeff) {
    maxPow = 0;
    int eq[1];
    coeffPtr = &eq[0];
    *coeffPtr = coeff;
}

Poly::Poly(int coeff, int maxPower) {
    maxPow = maxPower;
    int eq[maxPower+1];
    coeffPtr = &eq[0];

    for(int i = 0; i < maxPower; i++)
    {
        *(coeffPtr+i) = 0;
    }

    *(coeffPtr+maxPower) = coeff;
}

Poly::Poly(const Poly &other) {
    int eq[other.maxPow];
    coeffPtr = &eq[0];
    for(int i  = 0; i < other.maxPow; i++)
    {
        *(coeffPtr+i) = other.getCoeff(i);
    }
}

int Poly::getCoeff(int pow) const{
    return *(coeffPtr+pow);
}

在我的main方法中,对getCoeff(number)的初始调用将返回数组中的正确元素,但似乎在初始访问之后所有内容都会更改。

e.g.,
Poly A(5,7);
A.getCoeff(7); //returns 5
A.getCoeff(7); //returns random memory

我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:4)

您需要使用coeffPtr = new int[...]在堆上分配内存,而不是使coeffPtr指向局部变量,例如构造函数中的局部变量int eq[...]

局部变量的内存在堆栈上分配,一旦局部变量超出范围,就会/将被覆盖。在您的情况下,只要程序控制离开构造函数,coeffPtr就会成为指向内存可能随时更改的内存的悬空指针。写入此内存的情况更糟,会导致代码其他位置的数据损坏或随机崩溃。

如果在堆上分配内存,则还必须在析构函数中使用delete[] coeffPtr释放此内存,并在复制构造函数和复制赋值中处理内存...

(使用std::vector<int>代替int[]可能是一个更好的主意,因为它可以让您从内存管理中解脱出来。)

相关问题