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!
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, ie, 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.
Your variable K exists on the stack, which is just a chunk of memory that the program is using. So every stack entry still exists as an addressable memory location.
When you call theFunc, that address of K is pushed onto the call stack, and popped off in theFunc. When you do the assignment to the array location, the value of num (or K), meaning the value at the address that was passed in, is copied into the array.
In this case, passing by value would have the same effect since theFunc isn't changing num (or K).
链接地址: http://www.djcxy.com/p/82710.html上一篇: 堆叠和堆在C锐利
下一篇: 通过引用数组来传递堆栈分配的参数