我正在尝试动态声明2d数组并用随机数填充它们,然后创建一个函数来比较两个2d数组中的元素,如果它们相等,它将返回true
但是,尝试调用布尔函数时,我总是收到错误消息。
#include <iostream>
#include <cstdlib>
using namespace std;
bool isEqual(int *arr1[], int *arr2[], bool &eq, int row, int col){
for(int r = 0; r<row;r++)
{
for(int c= 0; c<col;r++)
{
if(arr1[r][c]==arr2[r][c])
eq = true;
}
}
return eq;
}
int main()
{
const int R = 3;
int * arr2D_a[R];
int * arr2D_b[R];
int C;
cout << "Enter number of columns: ";
cin >> C;
for (int r = 0; r < R; r++) {
arr2D_a[r] = new int [C];
arr2D_b[r] = new int [C];
}
for (int r = 0; r < R; r++) {
for (int c = 0; c < C; c++) {
arr2D_a[r][c] = rand() % 2;
arr2D_b[r][c] = rand() % 2;
}
}
bool result = false;
isEqual(arr2D_a,arr2D_b,result,R,C);
if (result==true)
cout << "\nThe 2 array are the same!\n";
else
cout << "\nThe 2 array are the differernt!\n";
for (int c = 0; c < C; c++) {
delete[] arr2D_a[C];
delete[] arr2D_b[C];
}
for (int r = 0; r < R; r++) {
delete[] arr2D_a[r];
delete[] arr2D_b[r];
}
system("pause");
}
答案 0 :(得分:5)
编辑,我自由地重写了您的代码。我发布的代码是在VS2017中编译的。
您的比较似乎还不错
#include <iostream>
#include <cstdlib>
using namespace std;
bool isEqual(int* arr1[], int* arr2[], const int row, const int col) {
for (int r = 0; r < row; r++)
{
for (int c = 0; c < col; c++)
{
if (arr1[r][c] != arr2[r][c])
return false;
}
}
return true;
}
int main()
{
const int R = 3;
int * arr2D_a[R];
int * arr2D_b[R];
int C;
cout << "Enter number of columns: ";
cin >> C;
for (int r = 0; r < R; r++) {
arr2D_a[r] = new int[C];
arr2D_b[r] = new int[C];
}
for (int r = 0; r < R; r++) {
for (int c = 0; c < C; c++) {
int value = rand();
arr2D_a[r][c] = value % 2;
arr2D_b[r][c] = value % 2;
}
}
bool result = isEqual(arr2D_a, arr2D_b, R, C);
if (result)
cout << "\nThe 2 array are the same!\n";
else
cout << "\nThe 2 array are the differernt!\n";
for (int r = 0; r < R; r++) {
delete[] arr2D_a[r];
arr2D_a[r] = 0;
delete[] arr2D_b[r];
arr2D_b[r] = 0;
}
return 0;
}
编辑2
我完全删除了函数调用中的bool ...
编辑3
要永久退出该程序,您必须提供一个返回值
另一个错误是,您不得执行第二个删除循环。因为您尚未动态分配此内存。
编辑4
重新编写了该函数,以取悦所有编译器=)
编辑5
我希望它是此答案的最后编辑^^我解决了内存问题。我和博士检查过。记忆,他说,一切都很好:D
答案 1 :(得分:2)
以上答案解决了大多数问题,但您会得到segfault
她。
for (int c = 0; c < C; c++) {
delete[] arr2D_a[c];
delete[] arr2D_b[c];
}
如果您在此处放置的东西大于3
std::cin >> C;
您需要做的是离开第二个循环:
for (int r = 0; r < R; R++) {
delete[] arr2D_a[r];
delete[] arr2D_b[r];
}
因为您在每个C
和arr2D_a[r]
中分配了arr2D_b[r]
个空间。