Hi,
I am trying to declare a 3D array with the size of 6,400 and 400 in each dimension using the code as following:

short matrix[6][400][400];

but actually it introduced a run time error "stack overflow" after surviving the compilation.So what's wrong with this code and how to fulfil my mission rightly?Thank u in advance.I use VS 2005 if it makes any difference.

Hi,
I am trying to declare a 3D array with the size of 6,400 and 400 in each dimension using the code as following:

short matrix[6][400][400];

So what's wrong with this code?

Nothing, with me it compiles and runs fine :)
Try compiling it as a release executable, you're probably compiling it in debugging mode ...

With that kind of error message I would be expecting that you have over or under run the array indexes.

If you post some more code, we can have a look.

But check that you don't let your indexes get to 400 or something.
(or negative!).

short usually 2 bytes, So in your case the 3d array Matrix has size of
2 X 6 X 400 X 400 = 1920000 bytes = 1.83 Mega Bytes.
Don't you think it is much?
If your program is using this much of memory, ask yourself " Do I really need this much"?
And besides, why aren't you using vectors instead of arrays?

#include<iostream>
#include<vector>

int main()
{
    using std::vector;
    const short d1=4,d2=400,d3=400,init_val=0;
    //Define it!!
    vector<vector<vector<short> > > Matrix(d1,
    vector<vector<short> >(d2,
    vector<short>(d3,
    init_val)));

    //Use it!!
    Matrix[0][25][14]=11;
    std::cout<<Matrix[0][25][14];
}

I know the syntax is a bit discouraging. Thats why most people go with some wrapper classes like that of Boost's multi_array
For time being cosider the following article from Dr.Dobb's

At the worst case, follow Tux's suggestion and stick with arrays.

Look at Project Properties|Linker|System and set the proper Stack Reserve Size parameter (in bytes - for example, set 3000000, see seedhant3s calculations). May be your IDE (VS 2005) has slightly different names for these parameters (I have VS 2008 now).

Better try to avoid large local (automatic) array allocations, especially in recursive functions.

Yet another straightforward approach (allocate a large array in the heap storage):

typedef short Matrix400[400][400];
int main()
{
    Matrix400* matrix = new Matrix400[6];
    cout << sizeof(Matrix400[6]) << endl; // sample
    ...
    delete [] matrix; // don't forget to free
    ...

I don't like multi-dimensional vectors (without wrappers). In addition to cumbersome declaration syntax, they have not contiguous data storage. Of course, tastes differ ;)

Do simple things as simple as possible...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.