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

时间:2015-01-02 09:50:41

标签: 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;
}

有什么问题?我想我不是在做正确的初始化。

2 个答案:

答案 0 :(得分:6)

这一行:

m_pArray = new T(m_rows * m_columns);

分配一个 T,其值为m_rows * m_columns(此语法是如何调用具有多个参数的构造函数,尽管此处只有一个参数)。

你可能意味着:

m_pArray = new T[m_rows * m_columns];

答案 1 :(得分:1)

我可以看到您的代码存在以下问题:

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