gpt4 book ai didi

C++为void指针分配一个字符串

转载 作者:行者123 更新时间:2023-12-01 14:15:51 25 4
gpt4 key购买 nike

我有下一个问题。我有这样的功能。

unsigned long FuncTest(void* name) { ... }

当我调用 FuncTest 时,我将制作这种形式

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;
}

我需要 FuncTest 将变量名称的值更改为字符串或字符之类的东西。有可能吗?

我输入了我拥有的代码,但无法正常工作。

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;
}

接下来是结果:

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

谁能帮帮我谢谢!

最佳答案

您按值将 test 传递给函数,因此您在函数内部对其所做的任何更改都不会反射(reflect)在调用程序中。

您需要通过引用传递它:

void FuncTest(void *&name)

关于C++为void指针分配一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62479644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com