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

Accessing and Manipulating an Array with Pointer in C++

本文关键字:操作 操作数 数组 访问 指针 c++      更新时间:2023-10-16

我正在尝试访问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

我做错了什么?

谢谢你!

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

局部变量的内存是在堆栈上分配的,一旦局部变量超出作用域,堆栈就会被覆盖。在您的示例中,一旦程序控制离开构造函数,coeffPtr就变成指向内存的悬空指针,其内容随时可能更改。写这个内存更糟糕,会导致代码中其他地方的数据损坏,或者随机崩溃。

如果你在堆上分配内存,那么你还必须在析构函数中使用delete[] coeffPtr来释放这些内存,并在复制构造函数和复制赋值中处理内存…

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