C 语言中的分割错误和矩阵问题



我正在尝试制作一个程序来读取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时,由于某种原因,我遇到了分段错误。

我做错了什么?

我做错了什么?

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

为了证明这一点main()变化

  int** img;

要成为

  int** img = NULL;

并在调用后立即添加storeImage()

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

相关内容

  • 没有找到相关文章