将数组传递给函数和在main中声明数组有什么区别?

What is the difference between passing arrays to function and declaring array inside main?

本文关键字:数组 声明 区别 main 什么 函数      更新时间:2023-10-16

将数组传递给function和在main中声明数组有什么区别?每个结构的优点是什么?例如,在第一个代码示例中,我将数组传递给一个函数,在第二个代码示例中,我在main中声明它。有什么区别?

版本1:

#include <iostream>
using namespace std;
void printArray(int theArray[], int sizeofArray);
//passive arrays to function..
int main() {
   int arr[3] = {44,23,22};
   int arry[5] = {56,23,11,23,55};
   printArray(arr, 3);
}
void printArray(int theArray[], int sizeofArray){
    for(int x =0;x<sizeofArray; x++){
        cout << theArray[x] << endl;
    }
}
版本2:

#include <iostream>
#include <string.h>
using namespace std;
int main() {
    int arr[3] = {44,23,22};
    int arry[5] = {56,23,11,23,55};
    for(int x=0;x<3;x++){
        cout << arr[x] << endl;
    }
}

正如Juanchopanza所指出的,在这两种情况下,您的数组都是在main函数中声明的。

主要区别在于代码组织。函数的目的是允许您对不同的参数执行任务。在第二个示例中,您仍然可以执行printArray(arry, 5)来打印第二个数组的内容,如下所示:

#include <iostream>
using namespace std;
void printArray(int theArray[], int sizeofArray);
//passive arrays to function..
int main() {
   int arr[3] = {44,23,22};
   int arry[5] = {56,23,11,23,55};
   printArray(arr, 3);
   printArray(arry, 5); // Let's see what's inside arry too !
}
void printArray(int theArray[], int sizeofArray){
    for(int x =0;x<sizeofArray; x++){
        cout << theArray[x] << endl;
    }
}

如果你想在第一个例子中做到这一点,你必须复制/粘贴循环,这将导致代码可读性降低,看看它有多难看:

#include <iostream>
#include <string.h>
using namespace std;
int main() {
    int arr[3] = {44,23,22};
    int arry[5] = {56,23,11,23,55};
    for(int x=0;x<3;x++){
        cout << arr[x] << endl;
    }
    for(int x=0;x<5;x++) {           // Here
        cout << arry[x] << endl;
    }
}

如果你必须打印十个不同的数组会发生什么?你是喜欢用不同的参数调用函数printArray十次还是你会复制/粘贴你的循环十次?