Reputation: 57
In this C++ code sizeof (ar) doesn't help me to find cols and rows variables and always gives me the same wrong cols and rows. How can I find the size of the matrix without passing sizeX and sizeY variables to the IsMagicSquare(arr) function? Can you help me to understand this problem and find a way to solve it?
int main()
{
int sizeX, sizeY;
cout << "Size of Matrix:";
cin >> sizeX >> sizeY;
int** arr = new int* [sizeY];
for (int i = 0; i < sizeY; ++i)
{
arr[i] = new int[sizeX];
}
cout << "Elements of the Matrix:";
for (int i = 0; i < sizeX; i++)
for (int j = 0; j < sizeY; j++)
cin >> arr[i][j];
if (IsMagicSquare(arr))
{
for (int i = 0; i < sizeX; i++)
{
cout << "\n";
for (int j = 0; j < sizeY; j++)
cout << arr[i][j];
}
}
else
{
for (int i = 0; i < sizeY; i++)
{
delete[] arr[i];
}
delete[] arr;
}
return 0;
}
bool IsMagicSquare(int** ar)
{
int rows = sizeof (ar)/ sizeof (ar[0]);
int cols = sizeof (ar[0]) / sizeof(int);
cout << rows << cols;
if (rows == cols)
{
int* ver = new int[rows]();
int* hor = new int[cols]();
int cross0=0;
int cross1=0;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
hor[i] += ar[i][j];
ver[j] += ar[i][j];
if (i == j)
cross0 += ar[i][j];
else if ((i+j) == cols)
cross1 += ar[i][j];
}
}
if (cross0 != cross1)
return false;
else
{
for (int i = 0; i < rows; i++)
if ((cross0 != ver[i]) || (cross1 != hor[i]))
return false;
}
}
else
return false;
return true;
}
Upvotes: 1
Views: 121
Reputation: 153850
Just sum the allocations you are making for a reasonable estimate:
sizeY * sizeof(int*)
.sizeY * sizeX * sizeof(int)
Of course, the size calculations you got in IsMagicSquare()
won’t work: sizeof
operates on the types rather than the actual allocated memory. That information is lost and can’t be recovered from the pointers. You are best off to use, e.g., a std::vector<std::vector<int>>
. That deals with automatic memory allocation and it tracks the sizes of the structure.
Upvotes: 1