首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C语言中关于分段错误和矩阵的问题

C语言中关于分段错误和矩阵的问题
EN

Stack Overflow用户
提问于 2019-06-10 00:44:12
回答 1查看 31关注 0票数 -1

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

我做错了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-10 00:50:50

我做错了什么?

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

要在main() change中证明这一点

  int** img;

成为

  int** img = NULL;

紧接在调用storeImage()之后添加

  if (NULL == img)
  {
    fprintf(stderr ,"img is NULL\n");
    exit(EXIT_FAILURE);
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56516490

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档