c - 带指针的矩阵二维数组

标签 c pointers matrix

<分区>

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

#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:我必须使用带有双指针的上述函数签名。

最佳答案

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

您需要使用 malloc 创建一个在函数中(记住 free 它)。您需要输入 #include <stdlib.h>在顶部与其他标题一起访问这些功能。您可以在下面看到使这项工作生效的更改。

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);

关于c - 带指针的矩阵二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44404189/

相关文章:

ubuntu - Octave 运算符 - : automatic broadcasting operation applied

java - 循环读取套接字

c - 如何在 C 中释放指向动态数组的指针?

c - 警告 : assignment makes integer from pointer without a cast in C

C 如何终止 char 的指针

javascript - 如何在一次rotate3d()调用上应用多个轴旋转?

C 时间程序 (NTP) 不绑定(bind)套接字

c - 获取socket读操作的进度

c++ - 轴对齐矩形测试中的点?

c++ - 错误:arma::memory::acquire():Armadillo 内存不足