adding another dimension with 2d pointer array

Hi I'm trying to add yet another dimension to my 2d pointer array I want each element for example ray[0][0] to now point to 4 new ints

here is my 2d pointer to pointer code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  #include <iostream>

using namespace std;

int main()
{
    int** ray = new int*[3];
    for(int i = 0; i < 3 ; i++){


        ray[i] = new int[4];
    }


}



I tried doing this below but I got an error,can anybody tell me why I get an error when I tried to do this? thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26



#include <iostream>

using namespace std;

int main()
{
    int** ray = new int*[3];
    for(int i = 0; i < 3 ; i++){


        ray[i] = new int[4];
    }

    for(int i = 0; i < 4; i++){

        ray[0][0] = new int[4];

    }


}









1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25



#include <iostream>

using namespace std;

int main()
{
    int** ray = new int*[3];
    for(int i = 0; i < 3 ; i++){


        ray[i] = new int[4];
    }

    for(int i = 0; i < 4; i++){

        ray[0][0] = new int*[4];

    }


}


and also this one thanks
Last edited on
its easier to go the other way when you need to reshape. So you can allocate 3d and access it 2d or 1d as needed...

for example, in 2d, you can go to 1d easily:

int x[10][10];

int* p = &(x[0][0]);

for(i = 0; i< 100; i++)
p[i] = i; //treat x as 1d for simpler iteration

this is a little awkward if not careful -- its prone to bugs and problems if you don't know what you are doing, and very easy to bungle a pointer even if you are an expert. Not recommended.

the even better way is to allocate 1d and access it manually by computing the 2d or 3d or nd offsets yourself. Then you can do just about anything you want to with your memory block. The advantages are many... no looping for allocation and deallocation, can reshape it to any dimensions that fit in the block at will, easy to copy, fast to iterate, and more.

but, to answer...
for a simple 3d pointer..

int ***x;
x = new int**[s1];
for(i =...s1...)
x[i] = new int*[s2]

for(i =...s1...)
for(j =...s2...)
x[i][j] = new int[s3];

x[1][2][3] = 4; //should be ok now that its been allocated.

and reverse all the loops to delete it after.













Topic archived. No new replies allowed.