I am new to C, and this struct, representing an image, is confusing to me. It’s used in this Graphics Gem.
Can someone explain the proper instantiation and use of the struct, especially with regard to the scanline pointer array?
typedef unsigned char Pixel;
typedef struct {
short Hres; /* no. pixels in x direction */
short Vres; /* no. pixels in y direction */
int Size; /* size in bytes */
Pixel *i; /* pixel array */
Pixel *p[1]; /* scanline pointer array; position (x,y) given by image->p[y][x] */
} Image;
Also: is the point to avoid the multiplication implicit when indexing a 2D array? Should it not then be **p which can be allocated to Vres * sizeof(size_t) and populated with the appropriate row pointers?
Update
I think I understand. Is this example block valid?
int m, n, y, x; /* Vres, Hres, index variables */
Image *image;
image = malloc(sizeof(Image) + (m - 1) * sizeof(Pixel*));
image->Hres = n;
image->Vres = m;
image->Size = m*n*sizeof(Pixel);
image->i = malloc(image->Size);
for (y=0; y<m; y++)
{
image->p[y] = image->i + (y * n);
for (x=0; x<n; x++)
{
image->p[y][x] = 0; /* or imageSource[y][x] */
}
}
/* use image */
free(image->i);
free(image);
Finally, on modern computers (with lots of memory), does it make sense to use such a scanline pointer array rather than a 2D array? In this case the only difference would be the implicit pointer multiplication.
The last member,
p, of the structureImageis used as a C89 flexible array member.Flexible array member is a C99 feature and before C99, people sometimes used what was called the struct hack to achieve a similar behavior with C89.
Here is how to dynamically allocate a
Imagestructure object with only one array element:and here is how to allocate a structure object with
narray elements:After correct initialization of the
Pixel *pointers in theparray, you can access thePixelvalues like this:Regarding the conformity of the struct hack, C99 Rationale says that
while a C Defect Report (DR #051) says that