use*_*572 3 c++ arrays pointers boolean function
我试图动态声明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");
}
Run Code Online (Sandbox Code Playgroud)
编辑我冒昧地重写你的代码.我发布的代码,在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;
}
Run Code Online (Sandbox Code Playgroud)
编辑2
我完全删除了函数调用中的bool ...
编辑3
要离开这个程序,你必须提供一个返回值
另一个错误是,你不能进行第二次删除循环.因为你还没有动态分配这个内存.
编辑4
重新设计功能以取悦所有编译器=)
编辑5
我希望它的最后编辑为这个答案^^我修复了内存问题.我和博士一起检查了一下.记忆,他说,一切都很好:D