0

Basically I want to set up a 3-dimensional array, but I want to dynamically allocate memory for it.

Say I read 3 variables from a file, all ints:
f, s, and v.
i want to allocate memory for
array[f][s][v]

array is part of a struct

How would I go about doing this?

I did search google, but only came up with solutions for 1D arrays

3
Contributors
3
Replies
4
Views
9 Years
Discussion Span
Last Post by dougy83
0

This is how I would do it, but there might be other ways.

int main()
{
    int ***arry;
    int f = 2, s = 3, v = 5;

    arry = new int**[f];
    for(int i = 0; i < f; i++)
    {
        arry[i] = new int*[s];
        for(int j = 0; j < s; j++)
        {
            arry[i][j] = new int[v];
        }
    }
}
0

Ok, thank you very very much. That was what I needed to know. I don't like the nested for loops, but it will work.

0

or you can just allocate a single block of memory and use some ugly dereference macros

#define deref(I,J,K) [I*s*v+J*v+K]
int *arry = new int[f*s*v];

arry deref(i,j,k) = 8;    // assign some value

cout << arry deref(m,n,o) << endl;  // read back some value

delete[] arry;

while the macro may not be the nicest solution, I prefer having all data for my array in the same contiguous block. It makes e.g. saving it to disk, or copying it in memory much easier. The clean up using a single delete[] is also preferable for me.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.