Search code examples
c++arraysheap-memorydynamic-memory-allocationstack-memory

Passing a stack allocated argument by reference to an array


I have a function say void theFunc(int num&, int* array) that takes in a an int by reference and an array pointer

theFunc(int num&, int* array)
{ array[0] = num; 
}

this is just an example, so the function does something simple

int main()
{ int k  = 3;
  int* theArray = new int[5];
  theFunc(k, theArray);

 delete[] theArray;
 return(0);
}  

My question is how is k, a stack allocated int instance, passed by reference to theFunc and stored in a dynamically stored array. I know that objects/argument can't just move between the stack and heap because they have specific stored memory addresses. I want to understand why this works, and what is happening under the hood (also if there's a difference in this case from passing by value).

Thanks!


Solution

  • The short answer is that k is not being "stored" in the dynamically allocated array. Rather, when you write int *theArray = new int[5] you are allocating a block of memory that can hold an array of five integers. In fact it already does hold five integers: having done nothing else, theArray[0] is a valid expression, i.e., it is an integer, although its value might be -32,768 or something like that. When you call theFunc with a reference to k, you are changing the value of theArray[0] to k by copy assignment, so you are assigning the value of k to the first element of the array. You are not storing anything new, you are just changing the value of something that has been already stored.

    Indeed, in this particular case nothing is gained or lost by passing num by reference. The observable behavior of the function as written would be identical if it were passed by value.