在 C++ 中将双数组初始化为零时崩溃

crash during intializiation of double array to zero in C++

我有以下代码

namespace VenkataLibrary {

template <class T>
class DoubleArray {
private:
    T* m_pArray;

    unsigned int m_uiBase; // base to note is array index starts from 0 or 1.
    unsigned int m_rows;
    unsigned int m_columns;

    class Row {
        unsigned int m_uiRow;
        DoubleArray& m_dblArray;
    public:
        Row(unsigned int rowNo, DoubleArray& dblArray) : m_uiRow(rowNo), m_dblArray(dblArray) { }

        T& operator[](const int column) {
            return m_dblArray.select(m_uiRow, column);
        }
    };

public: 

    DoubleArray(unsigned int rows, unsigned int columns) : m_rows(rows), m_columns(columns) {
        m_pArray = new T(m_rows * m_columns);
         memset((void*)m_pArray, 0x00, sizeof(T) * (m_rows-1) * (m_columns-1)); **// I am initializing memory to zero**
    }

    Row operator[] (unsigned int uiRow) {
        return Row(uiRow, *this);
    }

    T& select(unsigned int uiRow, unsigned int uiCol) {
        return m_pArray[uiRow * m_columns + uiCol];
    }
};

};

void main() {

    Array<unsigned int> myIntArray(10, 0);
    DoubleArray<unsigned int> myDblArray(10, 10);

    cout << myDblArray[1][1] << std::endl; **// System crashes here. And I am expecting zero** here.

    myIntArray[0] = 2;

     cout << myIntArray[0] << std::endl;
}

有什么问题?我想我没有正确地进行初始化。

我发现您的代码存在以下问题:

  • DoubleArray 违反了 Rule of Three.
  • DoubleArray 无法释放已分配的内存。
  • memset调用只初始化数组的一部分(最后一个参数应该是sizeof(T) * m_rows * m_columns)。
  • main 的 return 类型应该是 int(参见 What should main() return in C and C++?)。
  • 正如 immibis@ 所指出的,new 调用应该使用方括号来分配一个数组:new T[m_rows * m_columns]。使用括号分配一个标量。

这一行:

m_pArray = new T(m_rows * m_columns);

分配 one T,值为 m_rows * m_columns这里有一个论点)。

你的意思可能是:

m_pArray = new T[m_rows * m_columns];