【发布时间】:2019-07-07 12:14:05
【问题描述】:
我正在尝试动态声明二维数组并用随机数填充它们,然后创建一个函数来比较两个二维数组中的元素,如果它们相等,它将返回 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");
}
【问题讨论】:
-
你得到什么错误?
-
您在两个
for循环中使用相同的变量r。在循环范围内未使用的变量。是故意的吗? -
您在
for (int r = 0; r < R; r++) { arr2D_a[R] = new int [C]; arr2D_b[R] = new int [C]; }中有错字。您为数组索引使用了错误的r。 -
@MatthieuBrucher IDK。有很多错误/错别字,如果不知道 OP 有什么错误,很难知道。
-
试试
bool isEqual(int** arr1, int** arr2, bool &eq, int row, int col)
标签: c++ arrays function pointers boolean