简体   繁体   English

C ++,从字符串到char数组的转换

[英]C++, conversion from string to char array

I would like to perform the above mentioned operation, however I would like to make sure that the char array is exactly the same size with the string at hand. 我想执行上述操作,但是我想确保char数组与手边的字符串大小完全相同。

So the real question is, how can I make an array with a size that is going to be determined in the run time? 因此,真正的问题是,如何制作一个在运行时将要确定大小的数组?

allocating memory on the free store, and copying the string in one go: 在免费存储区上分配内存,并一次性复制字符串:

std::string s("abcdef");

...
char* chars=strdup(s.c_str());

You need to free the memory manually, of course. 当然,您需要手动释放内存。 Documentation eg on the man page . 文档,例如在手册页上 As @Loki mentions: freeing this memory is done through free(chars) , not through delete . 正如@Loki提到的: 释放此内存是通过free(chars) ,而不是通过delete Also, you need to include the <cstring> header. 另外,您需要包括<cstring>标头。

If you want to stay in the c++ world, use a vector ; 如果您想留在c ++世界中,请使用vector ; it can be created with two iterators to copy it's data from, and will allocate on the heap, and will cleanup by itself. 它可以用两个迭代器创建,以从中复制数据,并在堆上分配, 自行清理。 Isn't that a treat? 那不是一种享受吗?

std::vector<char> vec( s.begin(), s.end() );

You can create an array of size known at runtime with the "new" operator: 您可以使用“ new”运算符在运行时创建一个大小已知的数组:

char* res = new char[str.size()+1];
strncpy(res, str.c_str(), str.size()+1);
std::string s = "hello";
char* c = new char[s.length() + 1]; // '+ 1' is for trailing NULL character.

strcpy(c, s.c_str());
#include <string>

int main(int argc, char *argv[])
{
   std::string random_data("This is a string");

   char *array=new char[random_data.size()+1];

   // do stuff

   delete[] array;

   return 0;
}

Try: 尝试:

char* res = new char[str.size()+1]();   // Note the () makes sure it is '0' filled.
std::copy(str.begin(), str.end(), res); // Don't need to copy the '\0' as underlying
                                        // array already has '\0' at the end position.
...
delete [] res;                          // Must not forget to delete.

Or: (preferably) 或:(最好)

std::vector<char> res(str.begin(), str.end());

Or: If all you want to do is call a C-unction: 或者:如果您只想调用C函数,请执行以下操作:

str.c_str()

使用strlen()查找字符串的长度,然后使用malloc()一个具有该大小的char数组。

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

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