【问题标题】:Problems with segmentation fault and matrix in CC中的分段错误和矩阵问题
【发布时间】:2019-06-09 16:44:12
【问题描述】:

我正在尝试编写一个程序来读取 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 时,由于某种原因出现分段错误。

我做错了什么?

【问题讨论】:

  • 您想在调用storeImage()之前、期间和之后使用调试器(或一些printfs 来检查img 的值。
  • @alk 我这样做了,它工作正常
  • 你做了什么?什么工作正常。在这种情况下,您认为“通常”是什么?
  • 您需要在main 中初始化img,或者将其地址传递给一个函数(即传递一个int ***)来为您初始化它。或者将storeImage return img 作为其返回值(这可能是您的情况最简单的解决方案)。
  • OT:不需要传递文件指针的地址。在storeImage() 中将fil 设为FILE*,将所有(*fil) 设为fil 并传入fil

标签: c matrix segmentation-fault


【解决方案1】:

我做错了什么?

C 是按值传递的。所以storeImage()里面的img中存储的地址不会传递给storeImage()的调用者。

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

  int** img;

成为

  int** img = NULL;

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 1970-01-01
    相关资源
    最近更新 更多