Hanson
Hanson

Reputation: 35

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:

 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. I want to store the r,g,b in d_RGB[k][iCycleNum][jCycleNum],then I need to pass them to the host. 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. 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].

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.

Upvotes: 0

Views: 399

Answers (2)

sid
sid

Reputation: 1

 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++;
     }
    }
   }
  } 

Upvotes: 0

tebe
tebe

Reputation: 316

Actually a "classic" 3D array is organized in the memory as a 1D array (since the memory is 1D oriented).

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.

So the answer: just cast it to the right type you need.

Upvotes: 5

Related Questions