1

Following is a code to split an array. The
first output array will contain the input array entries in between the given two indices and the second output array will contain the rest of the entries.

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];
    }

The thing I can understand why it has parameters like int *&first and int *&second, arent they are same as just int first and int second but in this code they are used as pointers to dynamic arrays.

Crazy_Boy53
  • 241
  • 2
  • 4
  • 10
  • 6
    No, they aren't - `int*&` is a reference to a pointer to `int`. – UnholySheep Nov 15 '18 at 08:57
  • Here, `&` means "This is a C++ reference", not "take the address of". They use the same symbol for two different things which are only slightly more related to each other than they are to "bitwise and". – Daniel H Nov 15 '18 at 09:06
  • `*&first` would be the same as `first` if they were expressions and `*` and `&` were operators, but this is a declaration so `*` and `&` are not operators but parts of the type. – molbdnilo Nov 15 '18 at 09:19

1 Answers1

3

T *&foo declares a reference to a pointer to T. Don't confuse the ampersand in declarations and definitions with the address-of operator.

References to pointers are used if the called function needs to be able to modify the value of the pointer passed to it:

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;

Hint: Read types from right to left: T *& --> &* T --> reference (&) to pointer (*) to type T.

Swordfish
  • 12,971
  • 3
  • 21
  • 43