Search code examples
c++arraysmultidimensional-arraynew-operatordynamic-arrays

What is wrong in this array program?


I'm getting the same error at 2 different places in this program which is supposed to make a 1d, a 2d and a 3d array and store values and simultaneously display them. error: subscript requires array or pointer type / expression must have pointer-to-object type the error is for the expression 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
        }
    }

}


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


}

Solution

  • You used the variable name c twice: once for the array and second for the loop counter.