Reputation: 33
I have the next problem. I have a function like this.
unsigned long FuncTest(void* name) { ... }
When I call FuncTest, I'll make of this form
int main()
{
void* test = NULL;
cout << "Value of test before to call Function: " << test << endl;
FuncTest(test);
cout << "Value of test after to call Function: " << test << endl;
}
I need it that FuncTest change value of variable name for something like string o char. It is possible?
I put the code that I have it, but is not working.
void FuncTest(void* name)
{
char* NewValue = _strdup("Hello!");
cout << "Value of name in FuncTest before change: " << name << endl;
name = NewValue;
cout << "Value of NewValue in FuncTest: " << NewValue << endl;
cout << "Value of name in FuncTest after change: " << (char*)name << endl;
}
The Result is the next:
Value of test before to call Function: 00000000
Value of name in FuncTest before change: 00000000
Value of NewValue in FuncTest: Hello!
Value of name in FuncTest after change: Hello!
Value of test after to call Function: 00000000
Somebody Can help me Thanks!
Upvotes: 3
Views: 275
Reputation: 657
If you are going to change the value of test then just pass the pointer of test as a parameter of FuncTest function.
FuncTest(&test);
And FuncTest needs to be changed like this
void FuncTest(void** name)
{
char* NewValue = _strdup("Hello!");
cout << "Value of name in FuncTest before change: " << name << endl;
*name = NewValue;
cout << "Value of NewValue in FuncTest: " << NewValue << endl;
cout << "Value of name in FuncTest after change: " << (char*)*name << endl;
}
If you are going to change the value of parameter then you should send an address. test seems pointer but it is registered in stack register when function is called. And stack register variables are initialized after function executes. So you need to send pointer of test then even it's freed after function ends, the value will be remained. Hope this helps you to understand.
Upvotes: 1
Reputation: 223882
You passed test
to the function by value, so any change you make to it inside of the function won't be reflected in the calling program.
You need to pass it by reference:
void FuncTest(void *&name)
Upvotes: 4