Initializing 3D array c++?

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



MR_r = new long double**[m_nvalue];

MR_r[a] = new long double*[M_nodes[d]];
MR_r[a][b] = new long double[M_nodes[d-1]];

the result must be:

can anyone help me?


  • 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];
  • In addition to Lundin's words, who among others suggests using a sparse matrix, you can use a 3-dimensional std::vector:

    std::vector > > v;

    See e.g. to get the info about a 2D std::vector.

    See ya,
Sign In or Register to comment.

Howdy, Stranger!

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