我正在尝试编写一个程序来读取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 ()
时,由于某种原因我遇到了分段错误。
我在做什么错了?
答案 0 :(得分:0)
我在做什么错了?
C是按值传递。因此,存储在img
内部storeImage()
中的地址不会传递给storeImage()
的调用方。
要在main()
更改中证明这一点
int** img;
成为
int** img = NULL;
并在调用storeImage()
后添加
if (NULL == img)
{
fprintf(stderr ,"img is NULL\n");
exit(EXIT_FAILURE);
}