Initialization of array on heap

Radek Simko picture Radek Simko · Dec 31, 2010 · Viewed 36.3k times · Source

How do i manually initiate values in array on heap? If the array is local variable (in stack), it can be done very elegant and easy way, like this:

int myArray[3] = {1,2,3};

Unfortunately, following code

int * myArray = new int[3];
myArray = {1,2,3};

outputs an error by compiling

error: expected primary-expression before ‘{’ token
error: expected `;' before ‘{’ token

Do i have to use cycle, or not-so-much-elegant way like this?

myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;

Answer

langerra.com picture langerra.com · Dec 31, 2010

This is interesting: Pushing an array into a vector

However, if that doesn't do it for you try the following:

#include <algorithm>
...


const int length = 32;

int stack_array[length] = { 0 ,32, 54, ... }
int* array = new int[length];

std::copy(stack_array, stack_array + length, &array[0]);