C++数组作为参数传递给函数

1.如果使用引用,需要在函数形参写出引用数组的长度。

void bubblesort(int(&unsortarray)[10], const int &length) {
    for (int i = 0; i < length; ++i) {
        for (int j = 0; j < length - 1 - i; ++j) {
            if (unsortarray[j] > unsortarray[j + 1]) {
                swap(unsortarray[j], unsortarray[j + 1]);
            }
        }
    }
}

2.如果使用指针,则不需要指出数组长度。

void bubbleSort(int *unsortArray, const int &length) {
    for (int i = 0; i < length; ++i) {
        for (int j = 0; j < length - 1 - i; ++j) {
            if (unsortArray[j] > unsortArray[j + 1]) {
                swap(unsortArray[j], unsortArray[j + 1]);
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_37895339/article/details/79395130