如何通过引用传递2D数组?

时间:2013-05-28 02:43:47

标签: c pass-by-reference

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

1 个答案:

答案 0 :(得分:0)

如果要获取指向数组数组的指针,则应传递int***。幸运的是,没有必要这样做:你的功能可以简单地返回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;
}