如何通过引用访问调用中的结构类型?

时间:2017-06-12 05:31:28

标签: c struct initialization

现在我尝试使用ANSI C实现读取和操作的二进制数据。 我已经将结构类型定义为以下内容。

typedef struct {
    int     width;
    int     height;
    int     max;
    unsigned char **dummy;
    unsigned char **pixels;
} PPMImage;

然后在main函数中,我可以读取二进制数据。

int  main(int argc, char **argv)
{
    FILE *fpIn, *fpOut;
    PPMImage    img;

    if (fnReadPPM(argv[1], &img) != TRUE){
        return -1;
    } until here success

但是当我运行此代码时,我遇到了访问冲突。我不知道原因,如何通过引用访问结构中的结构类型?

    if (fnProc_grayPPM(&img) != TRUE){
        return -1;
    }

...
}


int fnReadPPM(char* fileNm, PPMImage* img)
{
    FILE* fp;

    if (fileNm == NULL){
        return FALSE;
    }

    fp = fopen(fileNm, "rb");   // binary mode
    if (fp == NULL){
        return FALSE;
    }

    img->pixels = (unsigned char**)calloc(img->height, sizeof(unsigned char*));
    img->luminance = (unsigned char**)calloc(img->height, sizeof(unsigned char*));

    for (int i = 0; i<img->height; i++){
        img->pixels[i] = (unsigned char*)calloc(img->width * 3, sizeof(unsigned char));
        img->luminance[i] = (unsigned char*)calloc(img->width , sizeof(unsigned char));
    }

    for (int i = 0; i<img->height; i++){
        for (int j = 0; j<img->width * 3; j++){
            fread(&img->pixels[i][j], sizeof(unsigned char), 1, fp);
        }
    }

    fclose(fp);

    return TRUE;
}




int fnProc_grayPPM(PPMImage* img)
{
    for (int i = 0; i < img->height; i++){
        for (int j = 0; j < img->width ; j += 3){

            img->luminance[i][j] = (img->pixels[i][j]); //<--- have a violation.

        }
    }

    return TRUE;
}

1 个答案:

答案 0 :(得分:1)

您对calloc()的来电是错误的。你用过了

  (unsigned char**)calloc(img->height, sizeof(unsigned char*));

img->height包含该点的不确定值。结果不能确定。

详细说明,img是一个未明确初始化的本地自动变量。因此,结构变量的各个成员变量包含不确定的值。因此,在您阅读变量之前,您需要将一些值写入它。

那就是please see this discussion on why not to cast the return value of malloc() and family in C..