gpt4 book ai didi

c - 在函数中重新分配输出指针

转载 作者:行者123 更新时间:2023-11-30 14:44:24 24 4
gpt4 key购买 nike

我想知道为什么当我运行以下代码时, t 的值调用 get 后是一样的和以前一样。

我感觉问题在于第 11 行 c = tmp 处的重新分配。 - 但希望有人能指出我正确的方向?

#include <stdio.h>
#include <tchar.h>
#include <windows.h>

BOOL get(COMPUTER_NAME_FORMAT f, WCHAR* c) {
DWORD s = 0;
WCHAR* tmp = NULL;
GetComputerNameExW(f, tmp, &s);
tmp = (WCHAR*)realloc(tmp, sizeof(WCHAR) * s);
GetComputerNameExW(f, tmp, &s);
c = tmp;
return TRUE;
}

void _tmain(int argc, _TCHAR* argv[])
{

WCHAR* t = TEXT("thisisatest");
BOOL res = get(ComputerNameDnsHostname, t);
printf("%Ls\n", t);
}

为了简洁起见,上面的代码已删除了错误处理代码。另外,我怀疑对 GetComputerNameExW() 的两次调用之间存在竞争条件。

最佳答案

您只需在 get(COMPUTER_NAME_FORMAT f, WCHAR* c) 函数中修改 main 的 t 指针的参数副本即可。

效果不会传播到 get 外部。您将 tmp 的值分配给一个临时指针,该指针在 get 返回后丢失。

get 中将 c 作为 WCHAR** c 传递,如下所示:

BOOL get(COMPUTER_NAME_FORMAT f, WCHAR** c){
//stuff
tmp = (WCHAR*)realloc(tmp, sizeof(WCHAR) * s);
*c=tmp;
//other stuff
}

关于c - 在函数中重新分配输出指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53514870/

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