Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to initialize an array with a buffer at time of declaration?

Tags:

c++

c++11

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.

like image 364
Adrian Avatar asked Dec 31 '14 17:12

Adrian


People also ask

What are the different ways of initializing array?

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.

What is the right way to initialize the array?

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.

How do you initialize an entire array with a single value in CPP?

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.


1 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);
}
like image 154
Benjamin Lindley Avatar answered Oct 29 '22 17:10

Benjamin Lindley