2

我对 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 正常工作的这两行,否则它不会。

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

头文件:

#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 的某些功能我没有正确理解。

4

1 回答 1

3

memset()这样使用:

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

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

于 2010-03-16T05:29:08.177 回答