【问题标题】:What is wrong in this array program?这个数组程序有什么问题?
【发布时间】:2012-04-09 13:09:45
【问题描述】:

我在该程序的 2 个不同位置遇到相同的错误,该程序应该创建一个 1d、一个 2d 和一个 3d 数组并存储值并同时显示它们。 错误:下标需要数组或指针类型/表达式必须具有指向对象的类型 错误在于表达式 c[r][c][depth]

#include<iostream>
using namespace std;
#define ROW 5
#define COL 5
 #define DEPTH 5

int main()
{
int *a;           // 1d array
a=new int [COL];

int (*b) [COL];          //2d array
b=new int [ROW][COL];

int (*c)[ROW][COL];
c=new int [ROW][COL][DEPTH]; // 3d array


//---------------------------------------------------------------------------------



// storing values in the arrays:

for(int i=0;i<COL;i++)
{
    a[i]=i+2;
    cout << a[i];
}

// 2d array
for(int r=0;r<ROW;r++)
{
    for(int c=0;c<COL;c++)
    {
        b[r][c]=r+c+2;
        cout << b[r][c];
    }
}

// 3d array
for(int r=0;r<ROW;r++)
{
    for(int c=0;c<COL;c++)
    {
        for(int depth=0;depth<DEPTH;depth++)
        {
            c[r][c][depth]=r+c+depth+2;             //error
            cout << c[r][c][depth];                 //same error
        }
    }

}


//-------------------------------------------------------------------------------------    


}

【问题讨论】:

    标签: c++ arrays multidimensional-array new-operator dynamic-arrays


    【解决方案1】:

    您两次使用变量名c:一次用于数组,第二次用于循环计数器。

    【讨论】:

      【解决方案2】:

      霍华德是对的。您在嵌套的 for 循环 for(int c=0;c&lt;COL;c++) 中将 c 重新声明为整数。

      您将 c 重新声明为循环范围的 int。您需要为循环提供不同的变量名称。

      例如:

      for(int k=0;k<COL;k++)
      {
          for(int depth=0;depth<DEPTH;depth++)
          {
              c[r][k][depth]=r+k+depth+2;             
              cout << c[r][k][depth];                 
          }
      }
      

      这应该可以编译并解决您的问题。将来使用更有意义的变量名可能会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多