繁体   English   中英

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

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

我想执行上述操作,但是我想确保char数组与手边的字符串大小完全相同。

因此,真正的问题是,如何制作一个在运行时将要确定大小的数组?

在免费存储区上分配内存,并一次性复制字符串:

std::string s("abcdef");

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

当然,您需要手动释放内存。 文档,例如在手册页上 正如@Loki提到的: 释放此内存是通过free(chars) ,而不是通过delete 另外,您需要包括<cstring>标头。

如果您想留在c ++世界中,请使用vector ; 它可以用两个迭代器创建,以从中复制数据,并在堆上分配, 自行清理。 那不是一种享受吗?

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

您可以使用“ 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;
}

尝试:

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.

或:(最好)

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

或者:如果您只想调用C函数,请执行以下操作:

str.c_str()

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

暂无
暂无

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

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