c++ - using pointer and address operator together -
i couldnt understand why using *&first (pointer , address operator together). mean? , when should use it?
void splitarray (int *a, 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]; int cnt1 = 0, cnt2 = 0; (int = 0; < size; i++) { if ((i >= ind1) && (i <= ind2)){ first[cnt1] = a[i]; cnt1++; } else { second[cnt2] = a[i]; cnt2++; } } }
what mean? , when should use it?
the &
symbol appearing after type defines reference type. thus, instance, int&
reference int
, my_object&
reference my_object
, , int *&
reference int*
(i.e. reference pointer int
).
when appears in function signature, means corresponding argument passed reference rather value: when passing value, function receives copy of argument; when passing reference, on other hand, function operates directly on argument being passed.
therefore, passing pointer reference means changes done function value of pointer affect original argument being passed.
in particular, these 2 instructions:
first = new int[firstsize]; second = new int[secondsize];
will assign dynamically allocated array first
, second
. therefore, in following code snippet (ellipses represent other arguments):
int* myfirst = null; int* mysecond = null; splitarray(..., myfirst, ..., mysecond, ...);
when returning splitarray()
, myfirst
, mysecond
point arrays allocated inside functions , assigned first
, second
, respectively.
if weren't passing pointers reference, value of myfirst
, mysecond
still null
after splitarray()
returns (because splitarray()
working on copy of pointers).
Comments
Post a Comment