我的数组值是如何被覆盖的
How are my array values getting overwritten
我正在创建一个int数组和一个重载((运算符的类的实例。这是课程:
模板CMatrix类{公用:
CMatrix(const int d);
CMatrix(const int d1, const int d2);
CMatrix(const CMatrix<M> &old); // copy ctor
~CMatrix();
int getXSize() {return s1;}
int getYSize() {return s2;}
CMatrix<M>& operator=(const CMatrix<M> &cm);// Asgnmnt constructor
CMatrix<M>& operator*(CMatrix<M> &cm);
inline M& operator()(const int i) {
ASSERT1(i<s1 && i>=0);
printf("CMatrix::operator(): i=%d, s1=%dn", i, this->s1);
return m[i];
}
inline M& operator()(const int i, const int j) {
ASSERT2(i<s1 && j<s2);
ASSERT2(i>=0 && j>=0);
return m[i*s2+j];
}
int s1, s2; // dimensions of array
M *m; // pointer to first element of matrix.
int dimensions;
声明:
int *oldRow=NULL;
CMatrix<int> *useRow=NULL;
以下是它们的定义:
oldRow = new int(nNodes);
useRow = new CMatrix<int>(nNodes);
我有一个循环来初始化它们:
printf(": &oldRow[0]=%un", oldRow);
printf(": &oldRow[7]=%un", &oldRow[7]);
printf(": &(useRow->s1)=%un", &(useRow->s1));
printf(": &(useRow->m)=%un", &(useRow->m));
for (int i=0; i<nNodes; i++) {
*(oldRow+i)=99;
printf("A: s1=%dn",(*useRow).s1);
printf("B: i=%dn", i);
(*useRow)(i)=0;
printf("C: i=%dn", i);
for (int j=0; j<nNodes; j++) nonZeroCount(i,j)=0;
}
最后,这里是输出。看看s1被覆盖:
: &oldRow[0]=39846784
: &oldRow[7]=39846812
: &(useRow->s1)=39846800
: &(useRow->m)=39846808
A: s1=8
B: i=0
CMatrix::operator(): i=0, s1=8
C: i=0
A: s1=8
B: i=1
CMatrix::operator(): i=1, s1=8
C: i=1
A: s1=8
B: i=2
CMatrix::operator(): i=2, s1=8
C: i=2
A: s1=8
B: i=3
CMatrix::operator(): i=3, s1=8
C: i=3
A: s1=99
B: i=4
CMatrix::operator(): i=4, s1=99
我知道这有点复杂;我试着让它尽可能简单,但仍然保留了所有相关的细节。我在useRow中使用了第二个普通的旧int数组,但我遇到了随机崩溃,所以我想我应该使用我的CMatrix类。
无论如何,请注意输出顶部的地址-useRow->s1和useRow->m都位于oldRow数组的中间!
我知道我一定做错了什么,但我不知道是什么。我也为它们使用了std::class,但它们也会随机崩溃,我认为int*oldRow可能不太容易出错。。。
oldRow = new int(nNodes);
由此,我怀疑oldRow
的类型是指向int
的指针。上面的那行将指针设置为指向单个整数,并初始化为nNodes
的值。
你的意思可能是
oldRow = new int[nNodes]{};
// ^ ^
// array C++11 default init of the elements
事实上,当您稍后访问oldRow
的"元素"时,您调用的是未定义的行为:通过在一个元素"数组"的边界之外写入,您覆盖了堆中的其他内容,损坏了堆并修改了其他分配的数据(在这种情况下,如果是您的类,则是该实例的成员字段(。
我也为它们使用了std::class,但它们也会发生随机崩溃,我认为int*oldRow可能不太容易出错。。。
一般来说,除非真的需要,否则不应该使用如上所述的原始分配数组。std::vector
类为运行时大小的数组提供了更好的方法。如果它随机崩溃,那么这是你做错了什么的直接迹象。
相关文章:
- C++找出覆盖同一行的数组
- C++/SDL 如何覆盖数组?
- 当将多个TypedArrayContents数组加载到V8数组中时(数组数组)时,最后一个元素将覆盖所有元素
- 为什么我的程序一直给我堆缓冲区溢出,即使我没有超出数组的界限或覆盖任何值
- 覆盖数组元素时如何调用构造函数
- c ++ 我的 char* 数组被最后一个添加的元素覆盖
- 初始值设定项列表覆盖动态多维数组的内存
- 编写一个函数,该函数将覆盖主函数数组中的值
- 将用户输入存储到2D数组中时要覆盖的值
- 从函数更新(覆盖)和显示数组
- 覆盖和扩展数组或矩阵,而不在特征中定义其大小
- 用静态数组覆盖指针属性
- 用较大的数组覆盖数组
- c++中的数组和覆盖-可以重用同一个对象吗?
- 我的数组值是如何被覆盖的
- 溢出字符数组每次都覆盖完全相同的字符串-为什么?
- 分配结构数组后覆盖的内存
- 为什么 std::getline 会覆盖包含文件名的字符数组
- 覆盖无符号字符数组中的值时出错
- 指针数组中的值被覆盖