C ++ Representing a 3D Array in a 1D Array

I want to store the byte aFloat value in Array pixels for each three-dimensional coordinate in a 1D array:

float aFloat = 1.0;
unsigned char* pixelsArray = new unsigned char[HEIGHT*WIDTH*3];

for (int i = 0; i < HEIGHT; i++)
{
   for (int j = 0; j < WIDTH; j++)
   {
      for (int k = 0; k < 3; k++)
      {
         pixelsArray[?] = aFloat;
      }
   }
}

What will happen in ??? I think it should also be + sizeof(float)somewhere in the index, if I'm not mistaken.

+5
source share
2 answers

Your inner line should be:

pixelsArray[(i * WIDTH + j) * 3 + k] = (unsigned char)(255.0 * aFloat);

This should give you a white image.

Make sure your target is really three bytes per pixel, not four (alpha channel or pad); if it's four, you just need to change 3above to 4.

+7
source

Do this first with a two-dimensional array:

0            1      ... W-1
W          W+1      ... 2*W-1
2*W      2*W+1      ... 3*W-1
  .           .     .       .
  .           .      .      .
  .           .       .     . 
(H-1)*W   (H-1)*W+1 ... H*W-1

So you will access this with

unsigned char* array = new unsigned char[H*W];
for(int r=0;r<H;r++)
  for (int c=0; c<H; c++)
    array[r*w+c]=...;

i*WIDTH*3 + j*3 + k

sizeof(float) , , , , Mike DeSimone.

+5

All Articles