简体   繁体   English

从3D阵列转换为1D阵列失败

[英]Conversion from 3D array to 1D array fails

The following program converts 3D array into 1D array with help of pointers . 下面的程序借助指针将3D数组转换为1D数组。 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 . 错误所在的行包含赋值运算符,该赋值运算符的两端都有指向int类型的指针。

#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 . // abc是指向int类型的指针的指针。

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 .
}

One method is to use nested for loops. 一种方法是使用嵌套的for循环。

Verify that your 1D array is large enough to contain the 3D slots . 验证1D阵列的大小足以容纳3D插槽

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. 注意:在上面的示例中,不需要或不要求使用指针。

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

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