steve
steve

Reputation: 33

Conversion from 3D array to 1D array fails

The following program converts 3D array into 1D array with help of pointers . Some conversion error is coming . The line in which error is coming contains assignment operator with pointer to pointer to int type on both sides .

#include<iostream>
using namespace std ;
int main()
{
// REPLACING 3D ARRAY WITH A 2D ARRAY AND THEN INTO A 1D ARRAY USING               POINTERS  .  
int abc [2][2][3] ;
int **p[3][2] ;
int *c[6] ;
//          // abc gives address of first element of 3d array ie first 2d   array .

// abc is pointer to pointer to pointer to int type .

int i , j ;     // * abc represents address of first 1d array of first 2d array .
for (i=0 ; i<=2 ; i++) // *abc +1:address of second 1d array of first 2d 
{                            // array .
for (j=0 ; j<=1 ; j++)
{
p[i][j] =  *(abc+i )  + j ; // conversion error comes here.

} 
}

for (i=0 ; i<=5 ; i++) 
{
for (j=0 ; j<=1 ; j++ )     
{
c[i] = *p[i][j] ;   
}

}

// entering array elements .
for (i=0 ; i<=5 ; i++)
{
cin>>* c[i] ;   

}

// required array elements .
for (i=0 ;i<=5 ;i++)
{
cout<<*c[i]<<"    "; // 3d array elements are accessed using 1d array  
}                                                        // of pointers .
}

Upvotes: 1

Views: 549

Answers (1)

Thomas Matthews
Thomas Matthews

Reputation: 57749

One method is to use nested for loops.

Verify that your 1D array is large enough to contain the 3D slots.

int a[2][2][2];
int c[2 * 2 * 3];
unsigned int index = 0;
for (unsigned int i = 0; i < 2; ++i)
{
  for (unsigned int j = 0; j < 2; ++j)
  {
    for (unsigned int k = 0; k < 3; ++k)
    {
      c[index++] = a[i][j][k];
    }
  }
}

Note: no pointers were required nor harmed in the above example.

Upvotes: 2

Related Questions