How Do I Use a Variable in new[]'s Value Initialization

拜拜、爱过 提交于 2019-12-12 01:54:13

问题


So when newing an array of chars I can value initialize:

const char* foo = new char[4]{'J', 'o', 'n', '\0'};

What I want to know is how to use a variable in that initializer_list:

const string initializer{"jon"};
const char* foo = new char[4]{initializer.c_str()}; // This doesn't work, can I make it work?

回答1:


You can use a variable, but you can't use a string and expect the compiler to magically split it up.

const char* ip = initializer.c_str();
const char* foo = new char[4]{ip[0], ip[1], ip[2], ip[3]};

Once you have a variable length, though, this doesn't work at all. You just have to allocate and then use string::copy to fill the array in a separate step.



来源:https://stackoverflow.com/questions/27504692/how-do-i-use-a-variable-in-news-value-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!