1

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 .
}
5
  • 1
    BTW, your p and c arrays are arrays of pointers. Is this intentional? Commented Jan 12, 2017 at 15:36
  • To convert multidimensional arrays into say 1d array or 2d array , we have to use pointers . This increases speed as pointer arithmetic is often faster than array indexing . Commented Jan 12, 2017 at 16:16
  • Can you prove that pointer arithmetic is faster than array indexing? Many processor instructions can load data using an index a lot faster than using pointer arithmetic. Some processors can perform loading from memory via pointer and an offset in one instruction. I don't see how using pointers is any faster. Commented Jan 12, 2017 at 16:27
  • Take the answer from my example and print the assembly language listing. Print the assembly language listing from your code using pointers. Compare. Next, profile the execution speed of both. Commented Jan 12, 2017 at 16:29
  • Why the conversion error is coming in my program ? Commented Jan 12, 2017 at 16:40

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.