Hey guys, I'm trying to create an array of integers with the size of 2,000,000. The program builds with no errors or warnings, however when I run it, it crashes. When I debug it I get a message saying Stack Overflow. After some time looking around in the debugger I narrowed down the source of my problem to the array. I understand this is a large array I'm trying to create, is there anyway around this or am I doing something wrong. The actual code I'm using to create the array is:
Before anyone asks, yes it has to be an array. Would it be better if I created the array dynamically instead?
You need to either increase the size of your stack or declare the array on the heap - make it global. Since this array is likely to be an important part of your project it's probably ok to make it a global, but I'd give it a descriptive name that will not likely be confused with something else.
I don't see the advantage of dynamic allocation for something like this. An array that size is unlikely to need to be freed before the program ends, and dynamic allocation will put it on the heap just as a global will. Using dynamic allocation will require the array be passed to functions and it's likely to be needed in many of them. By making it global you can treat it like a #defined constant and use it anywhere. As long as you've named it properly there shouldn't be any confusion with local variables.
And what is wrong with passing an array into the functions that require this array? By keeping the array local and properly passing it to only the functions that require the array will make troubleshooting problems much easier, in my opinion. Keeping variables as local a possible is usually considered the best approach.
How can you possibly tell that this string is going to be the center of attention? There has been no actual code provided. Why do you think passing a variable to many different functions as a parameter is bad?
But I beleive the passing of the variable with the proper use of "const" in functions that shouldn't modify the array is benificial. Also normally when I see someone using such a large array my first thought is do they really need that large array or is there a better way to accomplish the objective, but then I spent many years dealing with resourse constrained systems where memory was scarce.
That's 256,000 elements, and each element represents some number of people of that particular disease status, sex, age group, sexual activity level, alcohol status, viral load level, CD4 level, and virus resistance type. That array gets used everywhere, and when it does get used we usually have to iterate through the entire array. Making it global simplifies dealing with it. I'm not saying to use globals all the time. I'm just saying there are times when it is the best solution.