Reputation: 17
I'm trying to use nested for-loops and new, to write the C++ code that creates a 3x6x4 3D int array (with the name C) in the heap.
Heres my code so far:
#include <iostream>
using namespace std;
//#include "we.hh"
#define X 3
#define Y 6
#define Z 4
int main() {
//***<your_code_here>***
int *** C;
C = new int**[X * Y * Z];
int i, j, k;
for (int i = 0; i < X; i++)
C[i] = new int*[X];
for (int j = 0; j < Y; j++)
C[i][j] = new int[Y];
for (int k = 0; k < Z; k++)
C[i][j][k] = new int[Z];
I get an error on the last line saying invalid conversion from int* to int. Any help would be appreciated.
Upvotes: 0
Views: 148
Reputation: 88027
You need to nest your loops not sequence them, you also have one too many loops, and you've allocated the wrong number of pointers at each level. Like this
int *** C = new int**[X];
for (int i = 0; i < X; i++)
{
C[i] = new int*[Y];
for (int j = 0; j < Y; j++)
{
C[i][j] = new int[Z];
}
}
Upvotes: 0
Reputation: 126468
You're using C++ so don't use raw arrays or new.
std::array<std::array<std::array, Z>, Y>, X> C;
done.
Upvotes: 1