c - 将矩阵传递给 C 函数时出现段错误

标签 c segmentation-fault argument-passing

我无法弄清楚这段代码有什么问题(并且无法从之前的问答中找到任何建议):

#include<stdio.h>

void fld(const int **b){
int i, j ;
printf("Hello R\n");
for (i=0; i<3; i++){
    for (j = 0; j<3; j++)
        printf("%d", b[i][j]);
    printf("\n");
    }
return;
}

int main(){
int i, j;
int b[3][3] = {
            {1,1,1},
            {1,2,1},
            {2,2,2}
            };

fld((void **)b);
system("pause");
return;
}

我尝试将矩阵传递给函数 fld 并将其打印出来,但它在运行代码时不断报告段错误。

最佳答案

这是一个在堆上动态分配内存的版本。它的工作方式类似于 main() 参数 *argv[],即数组的数组(尽管在这种情况下行长度可能不同)。在此答案中,您不需要传递 fld() 的数组大小即可工作:而是告诉它何时停止!原因是,它是一个由数组指针组成的一维数组,每个数组指针也是一个一维数组。您也可以将相同的方法扩展到 3-D 数组。

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

int **intarray(int rows, int cols) {
    int r;
    int **arr = malloc(rows*sizeof(int*));   // here an array of pointers
    if (arr == NULL)
         return NULL;
    for (r=0; r<rows; r++) {
        arr[r] = malloc(cols*sizeof(int));   // here an array of ints
        if (arr[r] == NULL)
             return NULL;
    }
    return arr;
}

void fld(const int **b, int rows, int cols){
    int i, j ;
    printf("Hello R\n");
    for (i=0; i<rows; i++){
        for (j = 0; j<cols; j++)
            printf("%-5d", b[i][j]);
        printf("\n");
        }
return;
}

int main(void) {
    int i, j;
    int **b = intarray(3, 3);
    if (b == NULL)
        return 0;
    for (i=0; i<3; i++)
        for (j=0; j<3; j++)
            b[i][j] = i*100 +j;
    fld(b, 3, 3);

    // free() the memory
    return 0;
}

程序输出

Hello R
0    1    2
100  101  102
200  201  202

关于c - 将矩阵传递给 C 函数时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28840725/

相关文章:

c++ - 可变模板参数 : can I pick reference vs value depending on type?

c++ - 库 C 头文件在 Linux 上放在哪里

c - 通过转换为结构来分配给数组

c++ - 精度另外

c++ - 为什么这个 C++ 代码片段段错误?

python - 将绑定(bind)方法传递给函数的奇怪行为

c - 整数文字前导零的含义

c++ - C++ 中非常量列表迭代器的奇怪行为

c++ - 在从不再加载的动态库实例化的对象上使用在主代码库中定义的模板类方法时出现段错误

java - 将参数传递给实现的 java 方法