c - C 中的段错误和矩阵问题

标签 c matrix segmentation-fault

我正在尝试编写一个程序来读取 pgm 文件,将图像的像素值存储在动态分配的矩阵 img 中。

这是代码:

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

int height, width; // variables for the image height and width

typedef struct query {
    int x; // coordinate x of the position in which the user touched the image
    int y; // coordinate y of the position in which the user touched the image
    int crit; // criterion to be considered in segmentation
} queries;

void storeImage (FILE** fil, int** img) { // function that reads and stores the image in a matrix

    char trash; // variable that stores the content of 1st and 3rd line

    trash = fgetc(*fil);
    trash = fgetc(*fil);
    fscanf (*fil, "%d", &width);
    fscanf (*fil, "%d", &height);

    img = malloc (height * sizeof(int*));
    for (int i = 0; i < height; i++) {
        img[i] = malloc (width * sizeof(int));
    }
    fscanf (*fil, "%d", &img[0][0]);
    for (int i = 0; i < height; i++) { // for that fills the matrix img
        for (int j = 0; j < width; j++) {
            fscanf (*fil, "%d", &img[i][j]);
        }
    }

}

void verifyQuery (int x, int y, int c, int rep, int seg_regnum, int** img, float avg) {
    printf("%d ", img[x][y]);

}

int main (void) {

    FILE* fil = NULL;
    fil = fopen(test1.pgm, "r");
    if (fil == NULL) {
        printf("erro.\n");
        return 0;
    }

    int** img; // pointer to the matrix that represents the image

    storeImage(&fil, img);

    int k; // number of queries to the input image
    scanf("%d ", &k);

    queries q;

    for (int i = 0; i < k; i++) { // for to input the coordinates and criterion
        scanf("%d %d %d", &q.x, &q.y, &q.crit);
        float avg = 0;
        verifyQuery (q.x, q.y, q.crit, 0, i + 1, img, avg);
    }

    return 0;
}

一切都运行得很完美,直到我尝试运行verifyQuery ()。程序成功地将文件内容存储在矩阵 img 中。 但是,当我尝试在 verifyQuery () 中访问 img 时,由于某种原因出现段错误。

我做错了什么?

最佳答案

What am I doing wrong?

C 是按值传递。因此,存储在 storeImage() 内的 img 中的地址不会传递给 storeImage() 的调用者。

为了在 main() 更改中证明这一点

  int** img;

成为

  int** img = NULL;

并在调用storeImage()之后添加

  if (NULL == img)
  {
    fprintf(stderr ,"img is NULL\n");
    exit(EXIT_FAILURE);
  }

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

相关文章:

Android:对 View 应用任意变换

javascript - Node js 脚本崩溃 : Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

Java JNI 和省略号困惑

c - 球近似程序中用户定义归一化函数的奥秘

c++ - 为什么新编译的 g++ 说 "ld: cannot find -lg++"

c - 我在 c 中有一个段错误

正常崩溃,但不是 GDB?

c - ncurses printw() 不会在窗口中打印任何内容

c - 三重指针作为参数 - 矩阵乘法

matrix - 在 Mathematica 中选择/删除矩阵中的行/列列表的有效方法