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

2019-02-14 02:23发布

问题:

I want to store the byte value of aFloat in pixelsArray for each 3D 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 would go in the ?? I think it also needs to have + sizeof(float) somewhere in the index if I'm not mistaken.

回答1:

Your inside line needs to be:

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

This should give you an all-white image.

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



回答2:

Let's do this with a 2-dimensional array first:

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 would accesss 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]=...;

In your 3-dimensional array, you'd use

i*WIDTH*3 + j*3 + k

You do not need a sizeof(float) anywhere, though you probably need the value conversion that Mike DeSimone suggests.