我正在从纯文本 .pgm 文件中读取像素,并在读取像素后动态分配一个数组来保存像素,但是当我的readPGM
函数结束时,内部的数据似乎丢失了。我将一个传递int**
给一个函数,其中变成一个二维数组并被填充,但在readPGM
函数结束后它会丢失它的值。我怀疑int** pixels
通过引用传递会有所帮助,但我不确定如何解决这个问题,并希望得到任何建议。
#Function called from within readPGM to allocate an array
int** allocate_m(int rows, int cols){
int **matrix;
int i;
matrix = (int **)malloc(sizeof(int *) * rows);
for (i = 0; i < rows; ++i) {
matrix[i] = (int *)malloc(sizeof(int) * cols);
}
return matrix;
}
void readPGM(char* path, char version[3], int* cols, int* rows, int* grays, int** array){
FILE* pgm;
int pixel;
int count = 0;
pgm = fopen(path,"r");
//Reading the header of the file
fgets(version,3,pgm);
fscanf(pgm,"%d %d",&*cols,&*rows);
fscanf(pgm,"%d",&*grays);
//Allocating and filling the array of pixels
array = allocate_m(*rows,*cols);
while (fscanf(pgm,"%d",&pixel) == 1){
array[count/(*cols)][count%(*cols)] = pixel;
count++;
}
fclose(pgm);
}
int main(void) {
int cols, rows, grays;
char version[3];
int** pixels;
readPGM("/home/charlie/25.pgm", version, &cols, &rows, &grays, pixels);
return 0;
}
编辑:更正的readPGM
功能:
int** readPGM(char* path, char version[3], int* pcols, int* prows, int* pgrays) {
FILE* pgm = fopen(path,"r");
int pixel;
int count = 0;
fgets(version, 3, pgm);
fscanf(pgm, "%d %d", pcols, prows);
fscanf(pgm, "%d" ,pgrays);
int rows=*prows, cols=*pcols;
int** array = allocate_m(rows,cols);
while (fscanf(pgm,"%d",&pixel) == 1){
array[count/cols][count%cols] = pixel;
count++;
}
fclose(pgm);
return array;
}