gpt4 book ai didi

c++ - 如何将 vector 转换为 null 终止的 char **?

转载 作者:行者123 更新时间:2023-11-30 00:36:22 27 4
gpt4 key购买 nike

我正在尝试转换 std::vector<std::string>到以 NULL 结尾的 C 风格字符串数组 ( char * )。是否可以不使用 new 进行复制/malloc

基本上,我想在没有 new/malloc 的情况下将 vec 转换回与 arr 完全相同的东西。

#include <string>
#include <vector>
#include <stdio.h>
using namespace std;

void print(const char **strs)
{
const char **ptr = strs;
while(*ptr) {
printf("%s ", *ptr);
++ptr;
}
}

void print(std::vector<std::string> &strs) {
for(auto iter = strs.begin(); iter != strs.end(); ++iter) {
printf("%s ", iter->c_str());
}
}

void main()
{
const char *arr[] = { "a", "b", "c", "d", "e", "f", NULL };

vector<string> vec;

const char **str = arr;
while(*str) {
vec.push_back(*str);
++str;
}
vec.push_back((char *) NULL); //Doesn't work

//print(vec);
print((const char **) &vec[0]);
}

最佳答案

仅仅通过设置指向该 vector 开头的指针是不可能的,因为vector<string>不是您期望的连续字符。

                   addr1   addr2    addr3
^ ^ ^
| | |
+--------+--------+--------+----
| | | | | | |
| std:: | std:: | std:: |
+----> | string | string | string | ...
| | | | |
| +--------+--------+--------+----
|
|
|
vector<string>

addr1 , addr2addr3是内存中的随机地址。

因此,解决方案是遍历项目,读取字符串和字符并将它们放入您的 continues 数组中。

关于c++ - 如何将 vector<string> 转换为 null 终止的 char **?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16108062/

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