I have about 5000 lines of code which manipulates a large array in C++. The problem is that when I try to make the array even larger i.e. A[10000][10000], the gcc compiler throws me a segmentation fault error.
I believe the solution is to change the array to a dynamic array. Is it possible to do this by only changing the declaration of the array variable? Or would I have to change how the memory is accessed?
For example,
I have:
int A[10000][10000]; //rest of the code
Can I change this directly to:
int** A = new int*[size of input]; //rest of the code
while leaving the rest of the code intact?
Thanks
3
Your suggestion isn’t quite right.
int A[x][y];
(where ‘x’ and ‘y’ are expressions that can be evaluated to a constant at compile time) declares a single block of memory that is xysizeof(int) bytes long, and A[i][j] is translated to a reference to the I*y+jth value in the block. On the other hand,
int ** A = new int *[x];
allocates an array of x pointers to int arrays of unknown size, and does not initialize those pointers to point to anything specific. There are two consequences to this:
-
Before you can use the array you’ll also need to allocate a block for each row and store that in the top level array of pointers, and
- while you don’t need to change the syntax you’re using to access the array (A[i][j] will still work), be aware that the code the compiler generates has to load a pointer from the top level array and then preform arithmetic on that to find the location of the element, which is less efficient.
You should also, as mentioned in the comments, make sure you delete everything you create. Be aware that deleting arrays in c++ requires you to use “delete []” rather than the ordinary delete.
As you’re working in c++, I would recommend that you consider using the STL “array<>” type if you know the size of your arrays at compile time:
unique_ptr<array<array<int,y>,x> > pA(new array <array <int, y>, x> >);
auto &A = *pA;
should allow you to use the same syntax as you’re used to, allocate all the memory in a single block on the heap so using it is as efficient as your original code, and take care of deleting it automatically when it hours out of scope.
1