Проблемы с ошибкой сегментации и матрицы в C - PullRequest
0 голосов
/ 09 июня 2019

Я пытаюсь создать программу, которая читает файл 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. Однако, когда я пытаюсь получить доступ к img в verifyQuery (), я по какой-то причине получаю ошибку сегментации.

Что я делаю не так?

1 Ответ

0 голосов
/ 09 июня 2019

Что я делаю не так?

C передается по значению. Таким образом, адрес, сохраненный в img внутри storeImage(), не передается вызывающей стороне storeImage().

Чтобы доказать это в main() измените

  int** img;

будет

  int** img = NULL;

и сразу после звонка storeImage() добавить

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