问题描述
我正在尝试执行一个函数,该函数在给定2个参数的情况下调整由动态数组组成的矩阵的大小:新的行数和新的列数。我的问题是,当我将其调整为比原始矩阵大的矩阵时,应为0的新值类似于-4.31602e + 08。如果我不设置值而只是初始化数组,则不应该为0?
void Matrix::resize(int nRows,int nColumns) {
float** aux = new float* [nRows];
for (int i = 0; i < nRows;i++) {
aux[i] = new float[nColumns];
}
for (int i = 0; i < m_nRows; i++) {
for (int j = 0; j < m_nColumns; j++) {
if (i < nRows && j < nColumns) {
aux[i][j] = m_matrix[i][j];
}
}
}
for (int i = 0; i < m_nRows; ++i)
delete[] m_matrix[i];
delete[] m_matrix;
m_matrix = aux;
m_nRows = nRows;
m_nColumns = nColumns;
}
解决方法
您错误地认为浮点数已初始化为0。
尝试编译以下代码
float f;
std::cout << f;
..编译器至少会说“警告:'f'未初始化使用”。但毕竟可能打印0。
现在尝试
float* fp = new float;
std::cout << *fp;
delete fp;
编译器不警告,但您正在打印随机存储器内容... 访问未初始化的变量是未定义的行为。
编辑:智能指针将为您初始化值
auto fp = std::make_unique<float>();
std::cout << *fp << '\n';