c - int 矩阵中的段错误

标签 c pointers matrix segmentation-fault

我正在试验一些用指针定义 int 矩阵的基本 C 代码。

typedef int **Matrix;

Matrix createMatrix(int lines, int columns) {
    int i, j;
    Matrix m = (Matrix) malloc(sizeof(int) * lines * columns);
    for (i = 0; i < lines; ++i) {
        for (j = 0; j < columns; ++j) {
            m[i][j] = 0;
        }
    }
    return m;
}

int main(int argc, char**argv) {
    Matrix m = createMatrix(5, 10);
    // ...
    if (m[2][3] == 20) {
        // ...
    }
    return 0;
}

但是,这些 m[i][j] 访问会引发段错误。这里出了什么问题?星号太多?

我确信指向 int 指针的指针实际上与矩阵相同。

最佳答案

Matrix 数据项的分配假定您使用单个索引线性访问它。如果您想使用两个索引访问它,例如m[1][1],您需要分配每个维度:

Matrix m = malloc(sizeof(int *) * lines);

for ( int i = 0; i < lines; i++ )
    m[i] = malloc(sizeof(int) * columns);

另请注意,您 should not type cast malloc .

关于c - int 矩阵中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29111042/

相关文章:

c - 从 C 中的文件读取值时出现垃圾

c - 动态分配的指针数组不断重写自身

C指针循环中的奇怪行为

PDF 1.7 - CTM(电流转换矩阵)究竟是如何工作的?

matlab - 如何在 Matlab 中对矩阵中的列求和?

python - 如何根据条件从 NumPy 矩阵中获取行的子集?

c - 错误地将 ASCII 输出为最接近的素数

c - C 中的 volatile 变量

C: char 指针 & 段错误

c - 对结构成员的不优雅访问