Probably this is not a difficult question, but I am always a little bit confused on how to treat String type as an argument in Visual C++. I have the following to functions:
void function_1(String ^str_1)
{
str_1 = gcnew String("Test");
}
void function_2()
{
String ^str_2 = nullptr;
function_1(str_2);
}
After calling function_1
, str_2
is still equal to null
, but what I want to achieve is that str_2
is equal to Test
. So, how can I achieve that the content of str_1
is passed to function_2
?
Thanks for any advice.
When you pass an argument by reference, you pass a pointer to the value in memory. The function operates on the argument. When a function changes the value of an argument passed by reference, the original value changes. When you pass an argument by value, you pass a copy of the value in memory.
Passing by by reference refers to a method of passing the address of an argument in the calling function to a corresponding parameter in the called function. In C, the corresponding parameter in the called function must be declared as a pointer type.
The call by reference method of passing arguments to a function copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument.
int main() { int x=100; printf("Before function call x=%d \n", x);
Use a tracking reference:
void function_1(String ^%str_1)
{
str_1 = gcnew String("Test");
}
Explanation: Passing String ^
is like passing a pointer. Changes are only made to the local copy of the reference. String ^%
is like passing a reference to a reference... just as you would pass a pointer to a pointer when calling a function that should change the original pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With