c - 使用带有指向双指针的指针的 scanf()

标签 c multidimensional-array scanf pass-by-pointer

我觉得我已经尝试了我所知道的每一种组合来让它发挥作用,但我无法弄清楚。如何将 scanf() 转换为作为函数指针传递的 int**?我尝试搜索但找不到这个,如果它是重复的请告诉我,我会删除。它开始运行,并在输入一些值后出现段错误。

这是我的代码,我认为它在 setMatrix() 函数的 scanf() 行搞砸了:

#include <stdio.h>
#include <stdlib.h>

// create zero initialized matrix
int** callocMatrix(int rmax, int colmax) {  
        int **mat = calloc(rmax, sizeof(int*));
        for(int i = 0; i < rmax; i++) mat[i] = calloc(colmax, sizeof(int));
        return mat;
}

// fill matrix
void setMatrix(int ***mat, int r, int c){
    printf("Insert the elements of your matrix:\n");
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            printf("Insert element [%d][%d]: ", i, j);
            scanf("%d", mat[i][j]); // problem here??
            printf("matrix[%d][%d]: %d\n", i, j, (*mat)[i][j]);
        }
    }   
    return;
}

// print matrix
void printMatrix(int ***mat, int r, int c){ 

    for (int i=0; i<r;i++){
        for (int j=0; j<c;j++) {
                printf("%d ", (*mat)[i][j]);
        }
        printf("\n");
    }

}

int main(int argc, char *argv[]) {

    int r = 3, c = 3;

    int **mat = callocMatrix(r, c);

    setMatrix(&mat, r, c);

    printMatrix(&mat, r, c);
}

最佳答案

不需要使用三重指针***。传递二维数组将按原样工作。这是代码:

#include <stdio.h>
#include <stdlib.h>

// create zero initialized matrix
int** callocMatrix(int rmax, int colmax) {
    int **mat = calloc(rmax, sizeof(int*));
    for(int i = 0; i < rmax; i++) mat[i] = calloc(colmax, sizeof(int));
    return mat;
}

// fill matrix
void setMatrix(int **mat, int r, int c){
    printf("Insert the elements of your matrix:\n");
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            printf("Insert element [%d][%d]: ", i, j);
            scanf("%d", &mat[i][j]); // no problem here
            printf("matrix[%d][%d]: %d\n", i, j, mat[i][j]);
        }
    }
}

// print matrix
void printMatrix(int **mat, int r, int c){

    for (int i=0; i<r;i++){
        for (int j=0; j<c;j++) {
                printf("%d ", mat[i][j]);
        }
        printf("\n");
    }
}

int main(int argc, char *argv[]) {

    int r = 3, c = 3;

    int **mat = callocMatrix(r, c);

    setMatrix(mat, r, c);

    printMatrix(mat, r, c);
}

关于c - 使用带有指向双指针的指针的 scanf(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38134882/

相关文章:

java - 计算数组中的负数

c - 终止 While 循环 scanf ("%c",&ch)

C - 当输入不是 int 时提示用户输入有效 int 会导致无限循环

c++ - 如何正确使用QProcess写?

c++ - 在条件中省略 "> 0"?

c - 返回值的有用性不依赖于所有(仅按值调用)参数

c - Xcode Mach-O 链接器 ID 错误

uitableview - 具有多个部分的 XCODE TableView 和来自数组数组的委托(delegate)数据源 - 无法无误地删除行?

c - 如何在不强制使用 c 的情况下为每个线程分配任务,即每个线程在完成第一项工作后需要执行一些工作?

java - 二维阵列中所有岛之间的最大总和是多少?必须使用递归