简体   繁体   English

C ++表示一维数组中的3D数组

[英]C++ Representing a 3D array in a 1D array

I want to store the byte value of aFloat in pixelsArray for each 3D coordinate, in a 1D array: 我想在一维数组中为每个3D坐标存储aFloat的字节值(pixelArray):

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. 如果我没有弄错的话,我认为它还需要在索引中的某个地方加上+ sizeof(float)

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); 确保你的目标实际上是每个像素三个字节而不是四个(alpha通道或填充); if it is four, you'll just need to change the 3 above to a 4 . 如果它是4,你只需要将上面的3改为4

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. 尽管您可能需要Mike DeSimone建议的价值转换,但您不需要在任何地方使用sizeof(float)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM