gpt4 book ai didi

c++ - 从函数返回动态分配的 wchar_t* 数组

转载 作者:行者123 更新时间:2023-11-30 02:09:32 26 4
gpt4 key购买 nike

我有一个函数,其签名如下:

GetCustomers( wchar_t** Name,int *count);

在主要方法中:调用客户如下所示:

GetCustomers( Name,&count);

函数体如下:(由于客户数量未知,我尝试动态分配内存)

GetCustomers( wchar_t** Name,int *count)
{
//Logic to get customer count : Stored in int myCustomersCount
Names = new wchar_t*[myCustomersCount];

for (int i=0; i < myCustomersCount; i++ )
{
Names[i] = new wchar_t;
}

//Logic to get customer names in wchar_t* strName = "Name1";
Names[0] = strName;
*count = myCustomersCount;
}

我认为此实现将允许数组名称正确传递回 Main() 函数,并在堆上分配内存,但它似乎不起作用。这里有什么问题? myCustomersCount 在来电者中似乎是正确的。

PS:代码编译并执行,但 Main 中接收到的数组是垃圾。

最佳答案

您似乎在考虑 C,而不是真正的 C++。我会使用类似的东西:

std::vector<std::string> GetCustomers();

或(可能首选):

template <class outIt>
void GetCustomers(outIt output_iterator);

后者你会使用类似的东西:

std::vector<std::wstring> customers;

GetCustomers(std::back_inserter(customers));

第三个明显的可能性是为您的customers 类配备一个返回迭代器的begin()end() 成员函数到客户数据。

Edit2:这是一些经过测试的演示代码:

#include <stdio.h>
#include <string.h>
#include <wchar.h>

void GetCustomers(wchar_t ***names, int *count) {
static wchar_t *myCustomers[] = {
L"You",
L"Him",
L"Her"
};
int myCustomersCount = 3;
wchar_t **temp = new wchar_t *[myCustomersCount];

*count = myCustomersCount;
for (int i=0; i<myCustomersCount; i++) {
temp[i] = new wchar_t[wcslen(myCustomers[i])+1];
wcscpy(temp[i], myCustomers[i]);
}
*names = temp;
}

int main() {
wchar_t **customers;
int count;

GetCustomers(&customers, &count);

for (int i=0; i<count; i++)
printf("%S\n", customers[i]);
return 0;
}

关于c++ - 从函数返回动态分配的 wchar_t* 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5347954/

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