Блог пользователя PickledSausage

Автор PickledSausage, история, 3 года назад, По-английски

Hello,

So, I noticed several times that declaring some variables inside main gives runtime error, usually when they take much space, but still it does not seem it hits memory limit. For example, in these cases 134618509 134618526. In the first one arrays are declared outside main, while in the latter one inside main. Despite the fact they take up the same space the 2nd one gives runtime error. Could you please explain why this happens? Thanks in advance.

  • Проголосовать: нравится
  • +8
  • Проголосовать: не нравится

»
3 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Declaring global arrays takes less memory than declaring them inside any function (or for loops or whatsoever). The difference isn't big, but the accepted code hardly passed, so declaring the arrays in the main function won't pass.

That's why I declare global arrays and vectors. they take less memory, they are accessible by all functions without passing them as parameters and they are initiated with zeros instead of random values.

»
3 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

From here:

Also know that the stack or the "local storage" is used for storing temporary variables and function arguments which will be allocated to it when the function in which they belong to is called and "removed" when it returns. However the stack size is fixed and if there is no space in it to create them the program crashes. Global variables on the other hand doesn't have a memory limit as the space they need is automatically allocated on compile-time. Their life-time equals the application run-time as your "matrices" does because you had created them into the "main" function. So the choice now is simple — do you want to waste program time allocating & "removing" data and also risking a stack overflow or get your big data without a hassle — using global variables. Or if using real data — becoming friendlier with dynamic memory allocation.

Also, as he mentioned, you can use vectors instead of an array if you really want to declare it inside main and that doesnt happen. Just take care when youre declaring a vector of vectors because each vector needs to store a pointer, so you can end up passing the memory limit on some problems (like last div3's F)