【问题标题】:Conversion from 3D array to 1D array fails从 3D 数组到 1D 数组的转换失败
【发布时间】:2017-01-12 15:31:34
【问题描述】:

以下程序借助指针将 3D 数组转换为 1D 数组。一些转换错误即将到来。出现错误的行包含赋值运算符,其指针指向两边的 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 是指向 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 .
}

【问题讨论】:

  • 顺便说一句,您的 pc 数组是指针数组。这是故意的吗?
  • 要将多维数组转换为一维数组或二维数组,我们必须使用指针。这提高了速度,因为指针运算通常比数组索引更快。
  • 你能证明指针算法比数组索引更快吗?许多处理器指令可以使用索引加载数据,比使用指针算法快得多。一些处理器可以通过指针和一条指令中的偏移量从内存中加载。我看不出使用指针如何更快。
  • 从我的示例中获取答案并打印汇编语言列表。使用指针从您的代码中打印汇编语言列表。比较。接下来,分析两者的执行速度。
  • 为什么我的程序会出现转换错误?

标签: c++ pointers multidimensional-array


【解决方案1】:

一种方法是使用嵌套的for 循环。

验证您的 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];
    }
  }
}

注意:在上面的例子中,没有指针是必需的,也没有损害。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-02
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    • 2012-11-04
    • 1970-01-01
    • 2019-05-05
    相关资源
    最近更新 更多