我知道这个问题被问过很多次,但我找不到我的错误的解决方案
我正在尝试制作一个程序来检查给定的矩阵是否对称,用户输入测试用例的数量,然后输入大小,然后矩阵和输出是否为对称的
该程序可以正常工作,直到我尝试使用大于3的大小,该错误会中断,并且在调试时似乎在delete [] arrL处中断
#include <iostream>
#include <string>
using namespace std;
int n(char s)
{
switch (s)
{
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
}
}
int getnumber(string a)
{
string num = "";
for (int i = 0; i < a.size(); i++)
{
if (isdigit(a[i]))
num += a[i];
}
if (num.size() == 1)
{
return n(num[0]);
}
if (num.size() == 2)
{
return (n(num[0]) * 10) + (n(num[1]));
}
if (num.size() == 3)
{
return (n(num[0]) * 100) + (n(num[1]) * 10) + (n(num[2]));
}
}
bool matrix2(long int**p, int r)
{
int c = 0, u = 0, ss = 0;
for (int i = 0; i < r; i++)
{
for (int j = 0; j < r; j++)
{
if (p[i][j]<0)
return false;
}
}
long int*arrL = new long int[r];
long int*arrR = new long int[r];
for (int i = 0; i < r; i++)
{
for (int j = 0; j < i; j++)
{
arrL[c++] = p[i][j];
ss++;
}
}
for (int i = 0; i < r; i++)
{
for (int j = i + 1; j < r; j++)
{
arrR[u++] = p[i][j];
}
}
for (int i = 0; i < ss; i++)
{
int q = ss - i - 1;
long int a = arrR[i];
long int b = arrL[q];
if (!(a == b))
{
delete[]arrL;
delete[]arrR;
return false;
}
}
delete[]arrL;
delete[]arrR;
return true;
}
int main()
{
int t;
cin >> t;
for (int num = 0; num < t;num++)
{
int yy = num + 1;
string dimension;
cin.ignore();
getline(cin, dimension);
int r = getnumber(dimension);
long int**p = new long int*[r];
for (int w = 0; w < r; w++){
p[w] = new long int[r];
}
for (int w = 0; w < r; w++)
{
for (int ww = 0; ww < r; ww++)
{
cin >> p[w][ww];
}
}
bool result = matrix2(p, r);
if (result)
{
cout << "Test #" << yy << ": Symmetric." << endl;
}
else
{
cout << "Test #" << yy << ": Non-symmetric." << endl;
}
for (int i = 0; i < r; i++)
{
delete[]p[i];
}
delete[] p;
}
return 0;
}
最佳答案
将arrL和arrR分配为大小r,但是
arrL [c++] = p [i] [j];
被执行了r次以上,因此c超过了r,因此您破坏了堆。