gpt4 book ai didi

c++ - 创建用户定义类的实例并打开文件后,memset 出现问题

转载 作者:搜寻专家 更新时间:2023-10-31 02:00:04 29 4
gpt4 key购买 nike

我在使用 memset 时遇到了一个奇怪的问题,这与我在它之前创建的类以及我在构造函数中打开的文件有关。我正在使用的类通常读取一个数组并将其转换为另一个数组,但这并不重要。我正在使用的类是:

#include <vector>
#include <algorithm>
using namespace std;
class PreProcess
{
public:
PreProcess(char* fileName,char* outFileName);
void SortedOrder();
private:
vector< vector<double > > matrix;
void SortRow(vector<double> &row);
char* newFileName;
vector< pair<double,int> > rowSorted;
};

其他函数并不重要,因为我已经停止调用它们并且问题仍然存在。基本上我已经将它缩小到我的构造函数:

PreProcess::PreProcess(char* fileName,char* outFileName):newFileName(outFileName){
ifstream input(fileName);
input.close(); //this statement is inconsequential
}

我也在我的构造函数中读入了文件,但我发现如果我不读入矩阵而只是打开文件,问题仍然存在。基本上我已经缩小到如果我注释掉这两行 memset 正常工作,否则它不会。

现在回到我遇到的问题的上下文:我为矩阵编写了自己的简单包装类。它没有太多功能,我只需要在我的项目的下一部分中使用二维数组,让一个类处理所有事情对我来说更有意义。

头文件:

#include <iostream>
using namespace std;
class Matrix{
public:
Matrix(int r,int c);
int &operator()(int i,int j)
{//I know I should check my bounds here
return matrix[i*columns+j];
}
~Matrix();
const void Display();
private:
int *matrix;
const int rows;
const int columns;
};

司机:

#include "Matrix.h"
#include <string>
using namespace std;
Matrix::Matrix(int r,int c):rows(r),columns(c)
{
matrix=new int[rows*columns];
memset(matrix,0,sizeof(matrix));
}
const void Matrix::Display(){
for(int i=0;i<rows;i++){
for(int j=0;j<columns;j++)
cout << (*this)(i,j) << " ";
cout << endl;
}
}
Matrix::~Matrix()
{
delete matrix;
}

我的主程序运行:

PreProcess test1(argv[1],argv[2]);
//test1.SortedOrder();
Matrix test(10,10);
test.Display();

当我在输入行未注释的情况下运行它时,我得到:

0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 -1371727776 32698 -1 0
0 0 0 0 6332656 0 -1 -1 0 0
6332672 0 0 0 0 0 0 0 0 0
0 0 0 0 -1371732704 32698 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0

如果我将 memset 替换为:

for(int i=0;i<rows*columns;i++)
*(matrix+i) &= 0x0;

然后它完美地工作,如果我不打开文件它也能工作。如果有帮助,我在 Ubuntu 上运行 GCC 64 位版本 4.2.4。我假设我没有正确理解 memset 的某些功能。

最佳答案

您可以像这样使用 memset():

memset(matrix,0,sizeof(matrix));

这里的matrix是一个指针,所以sizeof(matrix)给出的是指针的大小,而不是数组的大小。要填充整个数组,请改用 columns * rows * sizeof(int)

关于c++ - 创建用户定义类的实例并打开文件后,memset 出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2452278/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com