Is there any way I can declare an array of char that is about 4,000,000 elements long? When I try to do so, the program crashes.
Printable View
Is there any way I can declare an array of char that is about 4,000,000 elements long? When I try to do so, the program crashes.
OS? Compiler?
For Windows, you can't have more than a megabyte in stack data, so you'll need to do something like:This will put it into heap memory, which has more space.Code:char *ptr = new char[4000000];
// ...
delete[] ptr;
At 4 MB, if you don't care about portability, you'll be best of using VirtualAlloc, which is designed to allocate very large amounts of memory.
Anytime you use arrays of that size, you get problems. Almost without exception you are better off using an external agent (like a database) to handle your data. The database developers have found most of the gotchas and know how to get around them. You won't.
CB is right - if you call malloc, your system may thrash for 20 seconds even if the memory allocation completes successfully.
This only only one of dozens of problems you'll encounter.
You have to use long int (int in MSVC++) to reference elements of an array that large. And so on.
Urgh, I'll stick with malloc for now, it seems to work well enough. Thank y'all
:D VirtualAlloc is guaranteed to scare any casual onlooker off.