Home > Blockchain >  How to pass a struct pointer between multiple functions
How to pass a struct pointer between multiple functions

Time:09-28

I'm trying to pass a pointer between multiple functions much like this:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

typedef struct {
    uint16_t w, h;
    uint32_t* pixels;
} Image;

void gen_img(Image** img)
{
    img->pixels = malloc(sizeof(uint32_t) * img->w * img->h); // Error by clangd: Member reference base type 'Image *' is not a structure or union
                                                              // Error by GCC: ‘*img’ is a pointer; did you mean to use ‘->’?

    for (int x = 0; x < img->w; x  )
        for (int y = 0; y < img->h; y  )
            img->pixels[y * img->w   x] = 0xFF000000;
}

Image* create_img(uint16_t w, uint16_t h)
{
    Image* img = malloc(sizeof(Image));

    img->w = w, img->h = h;

    gen_img(&img);
    
    return img;
}

int main(void)
{
    Image* img = create_img(32, 32);

    for (int x = 0; x < img->w; x  )
        for (int y = 0; y < img->h; y  )
            printf("%x\n", img->pixels[y * img->w   x]);

    return 0;
}

But I come across these errors that I can't interpret:

  • Clangd: Member reference base type 'Image *' is not a structure or union
  • GCC: '*img' is a pointer; did you mean to use '->'?

This example I made (and the pointer of pointer) is the result of multiple failed attempts, surely it's not the right way or I'm forgetting something.

EDIT: @user253751's answer is correct but I reproduced my example wrong, so we can't guess the original problem and the why of pointer pointer.

For the curious, I passed as a parameter a pointer defined in NULL, here is the usefulness of the pointer pointer.

CodePudding user response:

The immediate problem is that *img->pixels[blah] means *(img->pixels[blah]) i.e. the precedence is wrong.

Use (*img)->pixels[blah] instead.

The next problem is this code doesn't do what you think it does. It re-allocates the Image instead of the pixels array. Instead of:

*img = malloc(sizeof(uint32_t) * w * h);

I think you meant:

(*img)->pixels = malloc(sizeof(uint32_t) * w * h);
//    ^^^^^^^^

and in this case, since *img never changes, it doesn't need to be a pointer-to-pointer. You can just pass in the pointer to the Image as Image* img

  • Related