Is there a way to initialize a buffer array during declaration?

Basically, I am trying to do this:

char x[] = "hello"; char* y = new char[sizeof(x)](x); // won't work. 

demo

Is there any way to do this cleanly? There are no comments about DO NOT use raw arrays or raw pointers.

+5
source share
2 answers

Just write a function.

 template<typename T, size_t N> T* new_array(T const(&arr)[N]) { T* p = new T[N]; std::copy(std::begin(arr), std::end(arr), p); return p; } int main() { char x[] = "hello"; char* y = new_array(x); } 
+4
source

Path C:

 char* y = strdup(x); free(y); 
+2
source

Source: https://habr.com/ru/post/1210185/


All Articles