我想确定是否有办法确定动态分配的矩阵是否为正方形 (nxn)。
首先想到的是看看是否有办法查明指针是否即将指向无效的内存位置。但根据这些帖子:
C++ Is it possible to determine whether a pointer points to a valid object?
Testing pointers for validity (C/C++)
这是不可能的。
我想到的下一个想法是以某种方式使用 sizeof() 函数来查找具有方矩阵的模式,但对指针使用 sizeof() 将始终产生相同的值。
我首先创建一个大小为 nxn 的动态分配数组:
int **array = new int*[n]
for(int i = 0; i < n; i++)
array[i] = new int[n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
array[i][j] = 0;
}
}
现在我有一个大小为 nxn 的填充方阵。假设我正在实现一个打印方形二维数组的函数,但用户无意中创建了一个大小为 mxn 的二维数组并将其传递到我的函数中(由上面的代码完成,除了有更多行指针比组成列的元素,反之亦然),而且我们也不确定用户是否传递了对应于 n 行的 n 值或 < em>n 列:
bool(int **arr, int n){
for(int rows = 0; rows < n; rows++)
for(int cols = 0; cols < n; cols++)
cout << *(*(arr + rows) + cols) << " ";
// Is our next column value encroaching on unallocated memory?
}
cout << endl;
// Is our next row value out of bounds?
}
}
有什么方法可以通知这个用户(在出现段错误之前),这个函数只用于打印方形二维数组吗?
编辑:修正第 3 行
array[i] = new int[i]
到
array[i] = new int[n]
最佳答案
无法找到有关分配的信息。您可以做到这一点的唯一方法是将有关矩阵维度的信息存储在某处。指针只是指针。仅此而已。如果您需要的不仅仅是指针,则需要定义一个封装所有这些信息的类型。
class Matrix2D
{
public:
Matrix2D(int N, int M)
: m_N(N), m_M(M), m_data(new int[N*M]) {}
int N() const { return this->m_N; }
int M() const { return this->m_M; }
int* operator[] (int index) const
{ return m_data + m_M * index; }
private:
int m_N;
int m_M;
int* m_data;
};
关于c++ - 确保动态分配的矩阵是正方形的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57985288/