views:

203

answers:

3

Hello,

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;
  }
 }
+7  A: 

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.

leiz
Thanks, I think this can be done in C++ with the 'new' constructor. But do you know how to do this in Objective C?
Ryback
You could use old C malloc, or use std::vector I presume. Sorry I don't know Objective C very well.
leiz
Ok, thanks for your help!
Ryback
you can use malloc/free in Objective-C for dynamic memory management.
fbrereto
+2  A: 

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;
}
Kevin Loney
A: 

Got it... I used malloc and now it is working fine. Thanks a million guys!

Ryback