0

So I have a dynamic array in my struct:

struct Pixel {
    int r;
    int g;
    int b;
} Pixel;

struct Image {
    struct Pixel **rgb;
} Image;

Now when i come to use it, I create a fixed array (I know the width and height before coming to the pixels within the image). Here is my code for creating the fixed array:

struct Pixel rgbArray[HEIGHT][WIDTH];

But when I set the array in the struct to this new array:

myStruct->rgb = rgbArray;

warning: assignment from incompatible pointer type [enabled by default]

Because my program crashes when I run it to print the values in my array:

int x, y;
for(y = 0; y < HEIGHT; y++) {
    for(x = 0; x < WIDTH; x++) {
        struct Pixel newPixel = myStruct->rgb[y][x];
        printf("%d %d %d\n", newPixel.r, newPixel.g, newPixel.b);
    }
}
madcrazydrumma
  • 1,847
  • 3
  • 20
  • 38
  • A pointer to pointer of `struct Pixel` is not the same as an array of `struct Pixels`. I appears that you need to dynamically allocat it. And add the width and height to the `struct Image`. Also, `struct Pixel { } Pixel;` is declaring probably a *global* variable `Pixel` of type `struct Pixel`, is that what you want? – Iharob Al Asimi Jan 25 '16 at 21:13
  • @iharob yeah i want the global variable Pixel :) And how would I dynamically allocate it in the way I use it? – madcrazydrumma Jan 25 '16 at 21:15
  • It's a bad idea to use global variables in general. – Iharob Al Asimi Jan 25 '16 at 21:16
  • @iharob The other question doesn't help me solve my issue – madcrazydrumma Jan 25 '16 at 21:38
  • this is how to access your array `newPixel = myStruct->rgb[x+(y*WIDTH)];` – milevyo Jan 25 '16 at 21:38
  • I would declare rgb is a single pointer: i.e. struct Pixel *rgb; and access is like @milevyo recommends – bruceg Jan 25 '16 at 22:05
  • I bet if you printed out the location of rgb inside the loop printf("%pn\", &rgb); you'd see that the address looks like an invalid one. – bruceg Jan 25 '16 at 22:13

0 Answers0