简体   繁体   English

如何将3D阵列变成1D阵列?

[英]How to turn the 3D array into 1D array?

In my code, I defined a 3D array to store the date on CUDA kernel.The code just like this: 在我的代码中,我定义了一个3D数组将日期存储在CUDA内核中,代码如下所示:

 if(k<2642){
    double iCycle[100], jCycle[100];
    int iCycleNum = 0, jCycleNum = 0;
    for(double i=0; i<=1; i+=a, ++iCycleNum){
        iCycle[iCycleNum] = i;
        for(double j=0; j+i<=1; j+=c, ++jCycleNum){
            jCycle[jCycleNum] = j;    

            [...]       

            r=(int)color[indexOutput];
            g=(int)color[indexOutput+1];
            b=(int)color[indexOutput+2];

            d_RGB[k][iCycleNum][jCycleNum].x=r;//int3 (*d_RGB)[100][100]
            d_RGB[k][iCycleNum][jCycleNum].y=g;
            d_RGB[k][iCycleNum][jCycleNum].z=b;

        }                   
    }   
}

In every cycle, there is an r,g,b. 在每个周期中,都有一个r,g,b。 I want to store the r,g,b in d_RGB[k][iCycleNum][jCycleNum] ,then I need to pass them to the host. 我想将r,g,b存储在d_RGB[k][iCycleNum][jCycleNum] ,然后将它们传递给主机。 But in this case, every k has a different iCycleNum and jCycleNum, and I do not know the value of them, so the 3D array here is so awaste of space and may be it could bring some bugs. 但是在这种情况下,每个k都有一个不同的iCycleNum和jCycleNum,我不知道它们的值,因此这里的3D数组太浪费了空间,可能会带来一些错误。 I wonder if it is a way to change the 3D array into a 1D one like this: d_RGB[k+iCycleNum*x+jCycleNum*x*y] . 我想知道是否可以通过这种方式将3D数组更改为1D: d_RGB[k+iCycleNum*x+jCycleNum*x*y]

Sorry, my English is not so good to decribe it clearly, so if you can not get what I mean, please add a comment. 抱歉,我的英语不太好描述,因此,如果您听不懂我的意思,请添加评论。 Thank you. 谢谢。

Actually a "classic" 3D array is organized in the memory as a 1D array (since the memory is 1D oriented). 实际上,“经典” 3D数组在内存中组织为1D数组(因为内存是面向1D的)。

The Code: 编码:

int  aiTest[5][5][5] = {0};
int* piTest = (int*)aiTest;

for (int i = 0; i < 125; i++)
{
    piTest[i] = i;
}

does not make any memory violations - and the element aiTest[4][4][4] will have the value of 124. 不会造成任何内存冲突-元素aiTest [4] [4] [4]的值为124。

So the answer: just cast it to the right type you need. 答案就是:将其转换为所需的正确类型。

 int arr[5][6][7];
 int resultant_arr[210];
 int count=0;
 for(int i=0;i<5;i++)
 {
  for(int j=0;j<6;j++)
  {
   for(int k=0;k<7;k++)
   {
    if(count<210)
     {
       resultant_arr[count]=arr[i][j][k];
       count++;
     }
    }
   }
  } 

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

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