Basically, I'm trying to do this:
char x[] = "hello";
char* y = new char[sizeof(x)](x); // won't work.
demo
Is there a way to do this cleanly? No comments on DO NOT USE raw arrays, or raw pointers please.
There are two ways to specify initializers for arrays: With C89-style initializers, array elements must be initialized in subscript order. Using designated initializers, which allow you to specify the values of the subscript elements to be initialized, array elements can be initialized in any order.
Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.
int arr[10] = {5}; In the above example, only the first element will be initialized to 5. All others are initialized to 0. A for loop can be used to initialize an array with one default value that is not zero.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With