函数为什么可以将(int *&)作为参数?

时间:2018-11-15 08:55:51

标签: c++ arrays pointers

以下是用于拆分数组的代码。
第一个输出数组将在给定的两个索引之间包含输入数组条目,第二个 输出数组将包含其余条目。

void splitArray(int *arr, int size, int ind1, int ind2,
     int *&first, int &firstSize, int *&second, int &secondSize){
    firstSize = ind2 - ind1 + 1;
    secondSize = size - firstSize;
    first = new int[firstSize];
    second = new int[secondSize];
    for (int i = 0; i < ind1; i++)
    second[i] = arr[i];
    for (int i = ind1; i <= ind2; i++)
    first[i - ind1] = arr[i];
    for (int i = ind2 + 1; i < size; i++)
    second[i - firstSize] = arr[i];
    }

我能理解为什么它具有int *&firstint *&second之类的参数,因此它们与int firstint second相同,但是在此代码中使用了它们作为指向动态数组的指针。

1 个答案:

答案 0 :(得分:3)

T *&foo声明对指向T的指针的引用。不要将声明和定义中的与号与地址运算符混淆。

如果被调用函数需要能够修改传递给它的指针的值,则使用指针引用:

void bar(int *&ptr) {
    ptr = 42;  // change the value of the pointer  (pseudo ... 42 is most likely
    *ptr = 42; // change the value of the pointee   not a valid pointer value)
}

// ...

int *foo = nullptr;
bar(foo);
// foo == 42;

提示:从右到左读取类型:T *&-> &* T->引用(&)指向指针(*)以键入{{1 }}。

相关问题