c++中使用指针访问和操作数组
Accessing and Manipulating an Array with Pointer in C++
我正在尝试访问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[]
可能是一个更好的主意,因为它将您从内存管理中解放出来。)
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 重载操作程序时出错>>用于类中的字符串 memebr
- 控制允许动态运行c++的并发操作数
- 对字符串进行位操作
- 我可以在 C++ 中的函数体之外进行操作吗?
- MPI突然停止了对多个核心的操作
- 为什么C++逐位AND运算符在不同大小的操作数中表现为这样
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 对字符数组中的元素执行逐位操作
- 如何在directx/c++中进行平移/缩放操作
- 逐位操作的隐式类型转换
- 为什么一个向量上的多线程操作很慢
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 位移操作和位掩码未检测到重复字符
- 错误:如果(object1 == object2),“操作器==”无匹配(操作数类型为“ const class”和“
- 当操作数之一是负值C 时,模量操作
- 使用类作为操作数的操作在C++中成为可能
- OpenCV 错误:输入参数的大小不匹配(该操作既不是"数组操作数组")
- 间接操作需要指针操作数
- 错误:需要左键作为赋值的左操作数来执行操作