C语言中的分段错误与矩阵问题
我试图制作一个程序,读取pgm文件,将图像的像素值存储在矩阵C语言中的分段错误与矩阵问题,c,matrix,segmentation-fault,C,Matrix,Segmentation Fault,我试图制作一个程序,读取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 touc
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;
}
#包括
#包括
整数高度,宽度;//图像高度和宽度的变量
typedef结构查询{
int x;//用户触摸图像位置的坐标x
int y;//用户触摸图像位置的坐标y
int crit;//分段时要考虑的标准
}询问;
void storeImage(FILE**fil,int**img){//读取图像并将其存储在矩阵中的函数
char trash;//存储第1行和第3行内容的变量
垃圾=fgetc(*fil);
垃圾=fgetc(*fil);
fscanf(*fil、%d、&width);
fscanf(*fil、%d、&height);
img=malloc(高度*sizeof(整数*);
对于(int i=0;i
在我尝试运行verifyQuery()
之前,一切都运行得很好。程序成功地将文件内容存储在矩阵img
中。
然而,当我试图在verifyQuery()
中访问img
时,由于某种原因,我得到了一个分段错误
我做错了什么
我做错了什么
C是传递值。因此,存储在storeImage()
内部的img
中的地址不会传递给storeImage()
的调用者
要在main()中证明这一点,请更改
int** img;
将来
在调用storeImage()
add()之后
if (NULL == img)
{
fprintf(stderr ,"img is NULL\n");
exit(EXIT_FAILURE);
}
你想使用调试器(或一些<代码> Prtff s来检查<代码> IMG<代码>之前和之后调用“代码”> StureIGIVER()\代码> @ @ ALK我这样做了,它正常工作,你做了什么?什么是正常工作。你通常认为什么?在这种情况下?您需要在main
中初始化img
,或者将其地址传递给函数(即传递int***
)来初始化它。或者将storeImage
returnimg
作为其返回值(这可能是最简单的解决方案).OT:无需传递文件指针的地址。在storeImage()内部,使fil
成为文件*
,使所有(*fil)
成为fil
并传入fil
。
if (NULL == img)
{
fprintf(stderr ,"img is NULL\n");
exit(EXIT_FAILURE);
}