1

我正在从纯文本 .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;
}
4

1 回答 1

0

如果你想获得一个指向数组数组的指针,你应该通过int***. 幸运的是,不需要这样做:你的函数可以简单地 return int**

记得处理错误。

类似的东西(对不起,我没有编译它):

int** readPGM(char* path, char version[3], int* pcols, int* prows, int* pgrays) {
    FILE* pgm = fopen(path,"r");
    //Reading the header of the file
    fgets(version, 3, pgm);
    fscanf(pgm, "%d %d", cols, rows);
    fscanf(pgm, "%d" ,pgrays);

    int rows=*prows, cols=*pcols;
    //Allocating and filling the array of pixels
    int** array = allocate_m(rows,cols);
    if (array == NULL) {
        close(pgm); 
        return NULL;
    }

    int count;
    for (count = 0; count < rows * cols; count++) {
        int pixel;
        if (fscanf(pgm, "%d", &pixel) == 1) {
            free(array);
            array = NULL;
            break;
        }
        array[count / cols][count % cols] = pixel;
        count++;
    }
    fclose(pgm);
    return array;
}
于 2013-05-28T03:00:09.977 回答