我目前在使用以下C ++类时遇到问题,该类包含多维数据集的模型逻辑。构造函数创建一个动态的2d char数组,其中包含以下内容:
[ [0,0,0,0,0,0],
[1,1,1,1,1,1],
[2,2,2,2,2,2],
[3,3,3,3,3,3],
[4,4,4,4,4,4],
[5,5,5,5,5,5] ].
CubeModel.h
#ifndef CUBEMODEL_H_INCLUDED
#define CUBEMODEL_H_INCLUDED
#include <iostream>
class CubeModel
{
private:
const unsigned short m_faces;
const unsigned short m_fields;
char **m_cube_base_pointer;
public:
CubeModel(const unsigned short faces, const unsigned short fields);
~CubeModel();
void output();
};
#endif // CUBEMODEL_H_INCLUDED
CubeModel.cpp
#include "CubeModel.h"
CubeModel::CubeModel(const unsigned short faces, const unsigned short fields): m_faces(faces), m_fields(fields) {
m_cube_base_pointer = new char*[m_faces];
for (unsigned int i = 0; i < m_faces; ++i) {
m_cube_base_pointer[i] = new char[m_fields * m_fields];
memset(m_cube_base_pointer[i], i, sizeof m_cube_base_pointer[i]);
}
}
CubeModel::~CubeModel() {
for (unsigned int i = 0; i < m_faces; ++i) {
std::cout << (int) m_cube_base_pointer[i][0];
delete [] m_cube_base_pointer[i];
}
delete [] m_cube_base_pointer;
}
/*
Console output of the cube model
*/
void CubeModel::output() {
for (unsigned int i = 0; i < m_faces; ++i) {
for (unsigned int j = 0; j < m_fields * m_fields; ++j) {
std::cout << (int) m_cube_base_pointer[i][j] << std::endl; // output the model
}
}
}
的main.cpp
#include <iostream>
#include "CubeModel.h"
using namespace std;
int main() {
CubeModel cube = CubeModel(6, 3);
cube.output();
system("PAUSE");
return 0;
}
当我在main函数中创建一个CubeModel对象并调用输出方法时,我在Visual Studio中收到以下错误消息:
Cube.exe中0x00FC1DC8引发异常:0xC0000005:读取位置0x00000000时发生访问冲突。
CubeModel中的output()方法内引发了异常。
我在这里做错了什么?
答案 0 :(得分:1)
memset的第三个参数是您要设置的字节数。
然而
sizeof m_cube_base_pointer[i]
将为您指定指针的大小,而不是您刚刚分配的动态数组的大小。因此,为了获得您想要设置的正确字节数,您应该
sizeof(char) * m_fields * m_fields
代替。你的memset调用应该成为这个:
memset(m_cube_base_pointer[i], i, sizeof(char) * m_fields * m_fields);