ijverig
ijverig

Reputation: 2945

Treating 1D array (pointer) as 3D matrix at run time in C

I receive some image data as unsigned char *image = load_image(…);

This data is a 3D matrix: x (char),y (char) and channel (RGB) (char).

How can I access each element as image[x][y][channel]?

e.g. row 999, column 10000, green channel: image[999][10000][1]

Clarifications:

  1. I'd like to use C multi-dimensional array syntax:

    array[x][y][z], not array[x * height * channels + y * channels + z]

  2. I can access a 1D array as a 2D array:

    unsigned char (*imageMatrix)[height] = (unsigned char (*)[height])image imageMatrix[x][y] = 100

Upvotes: 0

Views: 261

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148870

If you can use this: unsigned char (*imageMatrix)[height] = (unsigned char (*)[height])image,, then your compiler supports Variable Length Arrays. VLA were introduced in C99 but were made back optional in C11.

But when VLA are supported, you can alias a 1D array to a 3D array exactly the same you alias it to a 2D array:

unsigned char (*imageMatrix)[width][channel] = (unsigned char (*)[width][channel])image;
imageMatrix[x][y][channel] = 100;

Upvotes: 2

Related Questions