gpt4 book ai didi

c++ - 如何找到传递给函数的矩阵的大小?

转载 作者:行者123 更新时间:2023-12-02 10:22:34 26 4
gpt4 key购买 nike

在此C++代码中,sizeof(ar)不能帮助我查找cols和rows变量,并且总是给我相同的错误cols和rows。
如何在不将sizeX和sizeY变量传递给IsMagicSquare(arr)函数的情况下找到矩阵的大小?您可以帮助我了解此问题并找到解决方法吗?

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;
}

最佳答案

只需对您正在分配的总和进行合理估算即可:

  • 外部数组:sizeY * sizeof(int*)
  • 内部数组:sizeY * sizeX * sizeof(int)

  • 当然,您无法通过 IsMagicSquare()进行大小计算: sizeof对类型进行操作,而不是对实际分配的内存进行操作。该信息会丢失,无法从指针中恢复。最好使用 std::vector<std::vector<int>>等。这涉及自动内存分配,并且它跟踪结构的大小。

    关于c++ - 如何找到传递给函数的矩阵的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59481373/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com