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

标签 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

我做错了什么?

谢谢!

最佳答案

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

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

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

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

关于c++ - 在 C++ 中使用指针访问和操作数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33056604/

相关文章:

c++ - 在默认初始化程序中使用 lambda 与使用成员函数

c# - 获取同一索引处相同元素的数量

c - dev c++ 和指向字符串的指针,程序挂起

C - 指针作为参数

c++ - 可变参数模板函数的仿函数

c++ - 使用 getline 代替 cin >>

javascript - 如何使用javascript映射将一个数组转换为另一个数组?

java - 计算 Java 数组中的非重复匹配对

C++ 风格的指针转换为整数

c++ - 为什么 Eigens mean() 方法比 sum() 方法快得多?