typedef struct{
int rows, cols; // matrix dimensions
int **element; // element array
}Matrix;
如果我要创建一个变量:
Matrix m;
我将如何在 Matrix
中创建一个 3x3 {{1,2,3},{4,5,6},{7,8,9}} 数组?
或者就此而言,我如何将任何大小的二维数组存储到 m.element 中?
我试过:
for (i=0; i<m.rows; i++)
{
for (k=0; k<m.cols; k++)
{
m.element=q;
q++;
}
}
最佳答案
您需要为矩阵分配空间。简单地为 m.elements[i][j]
赋值将尝试访问未知位置的内存,因为 m.elements
将未初始化并且将具有基本上随机的值.您的程序可能无法访问它,或者它可能没有正确对齐。构建一个函数来创建 rows
× cols
矩阵:
// Initialize and return a passed-in matrix.
// matrix must point to an allocated struct, not NULL.
void build(Matrix * const matrix, const size_t rows, const size_t cols) {
matrix->rows = rows;
matrix->cols = cols;
matrix->elements = malloc(rows * sizeof(int *));
for (size_t row = 0; row < rows; row++) {
matrix->elements[row] = malloc(cols * sizeof(int));
}
}
请注意,您可以创建任何形状的数组。如果您需要创建对称矩阵,则只需存储不低于主对角线的项。
由于这是动态分配二维数组,因此您有责任在完成后释放
它:
void destroy(Matrix * const matrix) {
for (size_t row = 0; row < matrix->rows; row++) {
free(matrix->elements[row]);
}
free(matrix->elements);
}
关于c - 如何使用 int ** 而不是 int [][] 二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20389995/