Reputation:
The following code is crashing my program. I found the problem is the size of the array. If I reduce the size to 320*320, it works fine. Does it make sense that this wound be a limitation? If so, what is a work around? I am coding in Objective C for IPhone. Any help would be appreciated.
Thanks!
int life_matrix[320*350];
x_size=320;
y_size=350;
for (int counter=0; counter < x_size; counter++)
{
for (int counter2=0;counter2 < (y_size); counter2++)
{
life_matrix[counter*(int)x_size+counter2] = rand()%2;
}
}
Upvotes: 1
Views: 1844
Reputation: 7553
leiz's advice is correct, you really should be allocating this dynamically otherwise you run the risk of running into a situation were the size of the array is larger than the available memory on the stack.
Also the formula you are using to map a 2-dimensional grid to a 1-dimensional array is incorrect. You should be multiplying by y_size instead of x_size.
life_matrix[counter*(int)y_size+counter2] = rand()%2;
or you could flip your counters
life_matrix[counter2*(int)x_size+counter] = rand()%2;
Another approach to solving this would be to use it as a 1-dimensional array for initialization:
for(int n = 0; n < x_size * y_size; ++n) {
life_matrix[n] = rand()%2;
}
Upvotes: 3
Reputation: 4052
The array is allocated on stack and usually the stack size is limited. If you need a big array, usually it is a good idea to allocate it on heap.
Upvotes: 7