During the exercise, you are required to write an array comparison function
#include "iostream"
using namespace std;
int isEqual(int a[], int b[]) {
int length_a = sizeof(a) / sizeof(a[0]);
int length_b = sizeof(b) / sizeof(b[0]);
if (length_a != length_b) {
return 200;
}
else {
for (int i = 0; i < length_a; i++) {
if (a[i] != b[i]) {
return 200;
}
}
return 30;
}
}
int main() {
int arr1[4] = { 1,2,3,5 };
int arr2[3] = { 1,2,3 };
int flag = isEqual(arr1, arr2);
cout << flag << endl;
return 0;
}
No matter how the values of the two arrays are changed, the output result of this function remains unchanged. What is the reason? ...Thank you~
In function parameter passing, arrays are passed into the function in the form of pointers, and there will be no call by value. In the function parameter, int arr[4] will degenerate into int *, and the 4 will be lost, so a in the isEqual function is actually just the first address of the array a.
If you want to pass in the array pointer and the size of the array at the same time, you need to use the array length as another formal parameter of the function:
For example:
Because you calculated the length of the two arrays incorrectly