【问题标题】:matrix 2d array with pointer [duplicate]带有指针的矩阵二维数组[重复]
【发布时间】:2017-06-07 05:27:13
【问题描述】:

这是我编写的用于获取矩阵值并显示它的代码

#include<stdio.h>   

int ** readMatrix(int rows, int cols)
{
    int i,j, matrix[rows*cols];
    int *b[rows];
    int **y=b;

    int k=0;
    for(k=0; k < rows; k++)
    {
        b[k]=&matrix[k*cols];
    }

    for(i=0; i< rows*cols; i++)
    {
        scanf("%d", matrix+i);
    }
    return y;
}

void displayMatrix(int **a, int rows, int cols)
{
    int k=0,j;
    for(k=0; k < rows; k++)
    {
        for(j=0; j < cols; j++)
        {
            printf("%d ", *(*(a + k) + j));
        }
        printf("\n");
    }
}

int main()
{   
    int rows,cols;
    printf("Enter the number of rows:\n");
    scanf("%d",&rows);
    if(rows <= 0)
    {
        printf("Invalid Input");
    }
    else
    {
        printf("Enter the number of columns:\n");
        scanf("%d",&cols);
        if(cols <= 0)
        {
            printf("Invalid Input");
        }
        else
        {
            printf("Enter the values:\n");
            int **a = readMatrix(rows, cols);
            displayMatrix(a, rows, cols);
        }
    }
}

程序卡在displayMatrix 的循环中,但如果我删除外部 for 循环,它会显示正常。

我得到的错误是Segmentation fault (core dumped)

我做错了什么?

PS:我必须使用带有双指针的上述函数签名。

【问题讨论】:

  • matrixreadMatrix 的局部变量,因此它的生命周期仅限于该函数的范围。
  • 请注意,您的代码中任何地方都没有二维数组。 matrix 是一维 VLA,而您传递的其他变量是指向指针的指针。
  • 在您的diaplayMatrix 函数中,您可以使用a[k][j] 而不是*(*(a + k) + j)。他们做同样的事情,但第一个更容易阅读。我还建议使用变量名 ij 而不是 kj,只是为了约定俗成。

标签: c pointers matrix


【解决方案1】:

readMatrix 中的问题是它返回一个指向该函数中的局部变量的指针。您不应该这样做,因为局部变量在函数返回后被释放,这就是您遇到分段错误的原因。

您需要在函数中使用malloc 创建一个(并记住free 它)。您需要将#include &lt;stdlib.h&gt; 与其他标题一起放在顶部才能访问这些功能。您可以查看下面的更改来完成这项工作。

int** readMatrix(int rows, int cols) {
    int i, j;
    int **matrix = malloc(rows * sizeof(int*));

    for(i = 0; i < rows; i++) {
        matrix[i] = malloc(cols * sizeof(int));
        for(j = 0; j < cols; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }

    return matrix;
}

现在有一个函数来释放这个数据结构可能会有所帮助。以下是您可以这样做的方法。

void freeMatrix(int **matrix, int rows) {
    int i;
    for(i = 0; i < rows; i++) {
        free(matrix[i]);
    }
    free(matrix);
}

然后更改main 函数以适应这些更改,如下所示。

int **a = readMatrix(rows, cols);
displayMatrix(a, rows, cols);
freeMatrix(a, rows);

【讨论】:

  • 我读到变量被释放,但内存保存了这些值,因此如果我们有内存位置,我们可以访问这些值。同样的代码在 readMatrix 中不使用指针数组 (b) 和 displayMatrix 中的外循环也可以正常工作。
  • @SaketShrivastava 从理论上讲,是的,但我不建议这样做。我很确定这是未定义的行为。
  • int ** readMatrix(int rows, int cols) { int i,j, matrix[rowscols];诠释* b; b = 矩阵; int **y=&b; for(i=0; icols; i++) { scanf("%d", matrix+i); } 返回 y; } void displayMatrix(int *a, int rows, int cols) { int i=0,j;诠释 k; k=icols; for(j=0; j
  • 这是我首先要做的。正如您在显示矩阵部分中看到的那样,有一个 k。如果我手动更改值,它会提供输出,但使用循环再次更改 k 会出错。
  • [link]ibb.co/fxyjvv这就是我正在做的事情