Meteory
Meteory

Reputation: 11

Two dimensional array size

I'm using Microsoft Visual Studio 2010. I have problem when I try to initialize this two dimensional array. - int A[480][640] .Error is that the stack is overflow.

Is this error pointing to a compiler or what? How can I fix this?

Thanks!

Upvotes: 1

Views: 308

Answers (3)

Neil Kirk
Neil Kirk

Reputation: 21763

As others mention, you are overflowing the stack which has a limited size. Large arrays should be dynamically allocated (on the heap) rather than placed on the stack. A vector is a dynamic array. Vector doesn't support 2d directly, but you can simulate it with a vector of vectors. Replace xsize and ysize with your sizes, which don't have to be constants anymore.

vector< vector< int > > A(ysize, vector< int >(xsize));

for (int y = 0; y < ysize; y++)
{
    for (int x = 0; x < xsize; x++)
    {
        A[y][x] = x * y;
    }
}

Note that y and x index are backwards. It is usually more efficient this way.

Upvotes: 2

Tricky12
Tricky12

Reputation: 6822

I believe you are indeed overflowing the stack. There are several ways to fix this, but the easiest two are to either make this static or move it outside of your main function.

static int A[480][640];

By making this static, you are basically making it use the data segment of memory as opposed to the stack (and overflowing it in this case because of the large allocation). In the image below, it would be in the 'initialized data', which is also where global variables are stored (the reason why the second option also works), outside of the stack/heap.

or

int A[480][640];
int main(int, char **) {
    //....
}

Upvotes: 1

Sharon Dorot
Sharon Dorot

Reputation: 542

What language are you using? 2D array is initialized like this: (C#) int[,] A = new int[x,y];

Upvotes: 0

Related Questions