#### Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

# Initializing 3D array c++?

Member Posts: 3
How to declare a 3d array that changes the the 2nd part....... i mean
MR_r[m_nvalue][a<-- this one changes][b]

M_nodes[0]=2
M_nodes[1]=1
M_nodes[2]=2

m_nvalue=3;

MR_r = new long double**[m_nvalue];

for(d=0;d<m_nvalue;d++){
for(a=0;a<M_nodes[d];a++){
MR_r[a] = new long double*[M_nodes[d]];
for(b=0;b<M_nodes[d-1];b++){
MR_r[a][b] = new long double[M_nodes[d-1]];
}
}
}

the result must be:
MR_r[0][0][0]
MR_r[0][0][1]
MR_r[1][0][0]
MR_r[1][1][1]

can anyone help me?

## Comments

• Member Posts: 3,711
A common mistake people make is when they are doing maths, graphics etc and are dealing with 3D-arrays, they automatically decide to use a 3D-array in C. There are two things you should be aware of:

- Multi-dimensional arrays in C don't follow any math logic. The dimensions are just there to tell the compiler how things are stored in the memory. That means you can define an array as array[x][y][z] or array[z][y][x] or array[y][z][x]... it all depends on how you as a programmer define them.

- Multi-dimensional, dynamic arrays is a real pain. You can't typecast between statically and dynamically allocated multi-arrays, which means that you can't pass them to ANSI C/C++ library functions. The dimensions usually just add confusion, dynamic allocation is slow, you risk memory leaks etc etc. So avoid them unless you can't make an alternative solution. Which of course depends on the nature of the data. An example of an alternative solution that can be used in some cases:

[code]typedef struct
{
int x;
int y;
Something data;
} Node;

Node nodes[n];
[/code]
• Member Posts: 754
In addition to Lundin's words, who among others suggests using a sparse matrix, you can use a 3-dimensional std::vector:

[code]
std::vector > > v;
[/code]

See e.g. http://www.codepedia.com/1/Cpp2dVector to get the info about a 2D std::vector.

See ya,
bilderbikkel
Sign In or Register to comment.