The statement int a2d[Size][Size];
is defining a Variable-Length Array, since Size
is not a compile-time constant. VLAs are not part of standard C++, so they should be avoided. The correct and standard way to allocate a dynamic array is to use the new[]
operator (see 1, 2), eg:
void sumGrid(int array[], int& Size)
{
cout << "Sum Grid" << endl;
int **a2d = new int*[Size];
for (int i = 0; i < Size; i++)
{
a2d[i] = new int[Size];
for (int j = 0; j < Size; j++)
{
a2d[i][j] = array[i] + array[j];
}
}
cout << " " << setw(7);
for (int j = 0; j < Size; j++)
{
cout << setw(7) << array[j] << ' ';
}
cout << endl;
for ( int k = 0; k < Size; k++)
{
cout << array[k] << ' ';
for (int l = 0; l < Size; l++)
{
cout << setw(7) << a2d[k][l] << ' ';
}
cout << endl;
}
cout << endl;
for (int i = 0; i < Size; i++)
{
delete[] a2d[i];
}
delete[] a2d;
}
Alternatively, using a 1d array that mimics a 2d array, so that the entire array is allocated sequentially in memory and not scattered around memory:
void sumGrid(int array[], int& Size)
{
cout << "Sum Grid" << endl;
int *a2d = new int[Size*Size];
for (int i = 0; i < Size; i++)
{
for (int j = 0; j < Size; j++)
{
a2d[(i*Size)+j] = array[i] + array[j];
}
}
cout << " " << setw(7);
for (int j = 0; j < Size; j++)
{
cout << setw(7) << array[j] << ' ';
}
cout << endl;
for ( int k = 0; k < Size; k++)
{
cout << array[k] << ' ';
for (int l = 0; l < Size; l++)
{
cout << setw(7) << a2d[(k*Size)+l] << ' ';
}
cout << endl;
}
cout << endl;
delete[] a2d;
}
That being said, you should avoid using new[]
/delete[]
directly, as it is error-prone, and particularly risks leaking memory if an error occurs. Use the standard std::vector
container instead, let it handle the memory management for you, eg:
Using a 2d sparse array:
#include <vector>
void sumGrid(int array[], int& Size)
{
cout << "Sum Grid" << endl;
std::vector<std::vector<int>> a2d(Size);
for (int i = 0; i < Size; i++)
{
a2d[i].resize(Size);
for (int j = 0; j < Size; j++)
{
a2d[i][j] = array[i] + array[j];
}
}
cout << " " << setw(7);
for (int j = 0; j < Size; j++)
{
cout << setw(7) << array[j] << ' ';
}
cout << endl;
for ( int k = 0; k < Size; k++)
{
cout << array[k] << ' ';
for (int l = 0; l < Size; l++)
{
cout << setw(7) << a2d[k][l] << ' ';
}
cout << endl;
}
cout << endl;
}
Using a 1d sequential array:
#include <vector>
void sumGrid(int array[], int& Size)
{
cout << "Sum Grid" << endl;
std::vector<int> a2d(Size * Size);
for (int i = 0; i < Size; i++)
{
for (int j = 0; j < Size; j++)
{
a2d[(i*Size)+j] = array[i] + array[j];
}
}
cout << " " << setw(7);
for (int j = 0; j < Size; j++)
{
cout << setw(7) << array[j] << ' ';
}
cout << endl;
for ( int k = 0; k < Size; k++)
{
cout << array[k] << ' ';
for (int l = 0; l < Size; l++)
{
cout << setw(7) << a2d[(k*Size)+l] << ' ';
}
cout << endl;
}
cout << endl;
}