简体   繁体   English

如何转换矢量<string>到 char* arr[]?</string>

[英]How can I convert vector<string> to char* arr[]?

Recently I want to convert vector to char* array[].最近我想将向量转换为 char* array[]。

So I had found the solution.所以我找到了解决方案。 But It was not safety way..但这不是安全的方式..

Here is my code这是我的代码

char** arr = new char* [4];

vector<string> vv;

// setting strings
for (int i = 0 ;i < 4; i++)
{
    vv.emplace_back("hello world");
}
// convert
for (int i = 0; i < 4; i++)
{
    arr[i] = new char[vv[i].size()];
    memcpy(arr[i], vv[i].c_str(), vv[i].size());
}

// prints
for (int i = 0; i < 4; i++)
{
    cout << arr[i] << endl;
}

// output
// hello world羲羲?솎솨
// hello world羲羲拂솽솨
// hello world羲羲
// hello world羲羲?펺솨

// delete memorys
for (unsigned index = 0; index < 4; ++index) {
    delete[] arr[index];
}

delete []arr;

Why does it happen string crash??为什么会发生字符串崩溃? Is there no safe way anymore?现在没有安全的方法了吗?

When you use memcpy , arr[i] is not guaranteed to be a null-terminated string.当您使用memcpy时,不能保证arr[i]是一个以 null 结尾的字符串。 To treat arr[i] as null terminated string, as inarr[i]视为 null 终止的字符串,如

cout << arr[i] << endl;

causes undefined behavior.导致未定义的行为。


You need couple of minor changes.您需要进行一些小的更改。

  1. Allocate one more byte of memory.再分配一个字节的 memory。
  2. Use strcpy instead of memcpy .使用strcpy而不是memcpy
arr[i] = new char[vv[i].size() + 1];
strcpy(arr[i], vv[i].c_str());

There's an easier way of doing this if you can maintain the lifetime of your initial vector .如果您可以保持初始vector的生命周期,则有一种更简单的方法。

for (int i = 0; i < 4; i++)
{
    arr[i] = vv[i].c_str();
}

This way you won't allocate no additional memory, however, you'd have to keep in mind that once your initial vector gets destroyed, that array will be corrupted as well.这样您就不会分配任何额外的 memory,但是,您必须记住,一旦您的初始vector被破坏,该数组也将被破坏。 But if you need such conversion for some simple synchronous api call within the same thread, that would do the trick.但是,如果您需要在同一线程中进行一些简单的同步 api 调用的转换,那就可以了。

In such cases I usually use this ugly construct.在这种情况下,我通常使用这种丑陋的构造。

arr[i] = new char[vv[i].size() + 1];
arr[i][vv[i].copy(arr[i], vv[i].size())] = 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM