问题描述
练习的过程中要求写一个数组比较的函数
#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;}
无论如何改变两个数组的值,该函数的输出结果不变,请问各位原因在哪?……谢谢了~
问题解答
回答1:在函数传参中数组都是以传指针的形式传入函数的,并不会出现传值调用。在函数形参中,int arr[4] 会退化成 int *,那个4就丢失了,所以isEqual函数中a实际上只是单纯的数组a的首地址。如果要想同时传入数组的指针和数组的大小就需要把数组长度作为函数的另一个形参:例如:
#include 'iostream'using namespace std;int isEqual(int a[],int length_a ,int b[],int length_b) { cout<<length_b<<length_a<<endl; 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,sizeof(arr1)/sizeof(int),arr2,sizeof(arr2)/sizeof(int)); cout << flag << endl; return 0;}回答2:
因为你两个数组长度求的不对
#include 'iostream'using namespace std;int isEqual(int a[], int b[], int length_a, int length_b) { cout << length_a << length_b << endl; if (length_a != length_b) {return 200; } else {for (int i = 0; i < length_a; i++) { cout << a[i] << b[i] << endl; if (a[i] != b[i]) {return 200; }}return 30; }}int main() { int arr1[5] = { 2,1,2,3,5 }; int arr2[3] = { 1,2,3 }; int length_a = sizeof(arr1) / sizeof(arr1[0]); int length_b = sizeof(arr2) / sizeof(arr2[0]); int flag = isEqual(arr1, arr2, length_a, length_b); cout << flag << endl; return 0;}