-1

I have just begun using C++, with a base in C. Having learned about Call by reference, I need to know,if in the following function I found online:

int insertSorted(int arr[], int n, int key, int capacity)
{
    if (n >= capacity)
        return n;

    arr[n] = key;
    return (n+1);
}

,which is used for insertion in an unsorted array, will the array in the main function get affected/changed? Since the arr[] argument in the function is not a reference variable, so how do any changes in this called function, reflect in the calling function? Is this correct code, if at all? I am basing my question upon the fact that call by value, creates copy variables and changes them, while call by reference changes the actual variables themselves. I'm sorry if this question is a bit silly. Any help in clearing up this concept would be great.

Thanks.

Sebastian Lenartowicz
  • 4,695
  • 4
  • 28
  • 39

1 Answers1

1

arr is effectively a pointer to the array. Thus, in your case it acts like a reference and the function changes the array arr points to.

If you want to do it more the C++ way you should use a std::vector<int> instead of a int[] for your array. std::vector has all features of a C-style array but takes care of memory management and the actual number of elements.

In case of a std::vector you really have to pass a reference (std::vector &), otherwise the function will receive a copy of the entire array.

bjhend
  • 1,538
  • 11
  • 25
  • "arr is effectively a pointer to the array" `arr` is actually a pointer to an `int`. A pointer to an array is something different. – newacct Aug 05 '17 at 02:24
  • That's why I wrote "effectively" to point out it is not _strictly_ a pointer to an array. – bjhend Aug 05 '17 at 10:53