【问题标题】:C double/triple pointer to struct指向结构的 C 双/三指针
【发布时间】:2016-12-19 19:35:31
【问题描述】:

我想更改函数内部一些结构变量的值。

这是我的变量声明:

BMPCOLOR **tBMPImg;
BMPCOLOR **tBMPGrey;

这是我在主函数中的函数调用:

greyscale(tBMPImg, tBMPGrey, &tBMPInfoblock, &tBMPHeader);

在这里你可以看到我想要改变变量值的函数:

void greyscale(BMPCOLOR ***tBMPImg, BMPCOLOR ***tBMPGrey, BITMAPINFORMATIONSBLOCK *tBMPInfoblock, BITMAPFILEHEADER *tBMPHeader) {      //Grau = 0,299*Rot + 0,587*Grün + 0,144*Blau
double dGrey;
int iX;
int iY;

FILE *fpGrey;
fpGrey=fopen("grau.bmp", "w+");

fwrite(tBMPHeader, sizeof(&tBMPHeader), 1, fpGrey);        //probably wrong too
fwrite(tBMPInfoblock, sizeof(&tBMPInfoblock), 1, fpGrey);

for(iX=0;iX<tBMPInfoblock->lbiWidth;iX++) {
    for(iY=0;iY<tBMPInfoblock->lbiHeight;iY++) {
        dGrey=0.299* tBMPImg[iY][iX]->cRed + 0.587 * tBMPImg[iY][iX]->cGreen + 0.144 * tBMPImg[iY][iX]->cBlue;  //Error: "error reading variable dGrey"
        tBMPGrey[iY][iX]->cRed=dGrey;                                                                           //i guess something is with those pointers wrong
        tBMPGrey[iY][iX]->cGreen=dGrey;
        tBMPGrey[iY][iX]->cBlue=dGrey;
    }
}
for(iX=0;iX<tBMPInfoblock->lbiWidth;iX++) {
    for(iY=0;iY<tBMPInfoblock->lbiHeight;iY++) {
        fputc(tBMPGrey[iY][iX]->cBlue,fpGrey);
        fputc(tBMPGrey[iY][iX]->cGreen,fpGrey);
        fputc(tBMPGrey[iY][iX]->cRed,fpGrey);
    }
    fwrite("0", tBMPInfoblock->lbiWidth % 4,1,fpGrey);
}

fclose(fpGrey);

我在 main 中使用指向 struct 的指针,但我不知道如何在另一个函数中处理它。在其他情况下,例如:How to work with pointer to pointer to structure in C? 是解决方案(*foo)-&gt;member = 1;,但它在我的程序中不起作用。

我已经读到在这种情况下我必须使用指向指针的指针。 我想问题是我只是从变量中获取地址。

【问题讨论】:

    标签: c pointers struct


    【解决方案1】:

    如果您正在访问数据结构,则无需添加额外的指针间接层(即另一个 *)。如果您正在分配内存并且您需要将新的内存地址发送回调用者,您只需要添加另一个 *。只需像这样使用您现有的声明,并将 -&gt; 运算符替换为 . 运算符。

    void greyscale(BMPCOLOR **tBMPImg, BMPCOLOR **tBMPGrey, ...
    ...
    
            dGrey=0.299* tBMPImg[iY][iX].cRed + 0.587 * tBMPImg[iY][iX].cGreen + 0.144 * tBMPImg[iY][iX].cBlue;
    ...
    
            tBMPGrey[iY][iX].cRed=dGrey;          
    

    不请自来的建议:

    我应该指出,您对BMPCOLOR **img 的定义称为参差不齐或参差不齐的图像,在大多数情况下,这不是您想要的效率。你想要的是

    BMPCOLOR* img;
    

    创建图片

    img = malloc(NUM_COLUMNS * NUM_ROWS * sizeof(BMPCOLOR));
    

    并像访问像素

    img[y * NUM_COLUMNS + x].cRed = 
    

    【讨论】:

    • 感谢您的解决方案和建议。
    猜你喜欢
    • 2011-11-30
    • 2020-11-15
    • 2021-07-14
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 2021-01-12
    相关资源
    最近更新 更多