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;
Creating an array in the heap allocates a new array of 25 ints and stores a pointer to the first one into variable A. double* B = new double[n]; allocates an array of 50 doubles. To allocate an array, use square brackets around the size.
The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.
An array may be partially initialized, by providing fewer data items than the size of the array. The remaining array elements will be automatically initialized to zero.
Declare Arrays in C/C++int arr[5]; The above code creates a static integer array having size 5. It will allocate the memory on the stack, and the scope of this memory is limited to the scope of the function in which the array is declared. This memory will be freed automatically once we exit the function.
This can be accomplished today with the following syntax:
int * myHeapArray = new int [3] {1, 2, 3};
Notice you have to match the size of the structure you're allocating with the size of the initializer-list.
Since I'm replying to a question posted years ago, it is worth mentioning that modern C++ discourages the use of new
, delete
and native (or naked) pointers. The use of handlers such as std::unique_ptr
and std::shared_ptr
are favored instead, since they automatically release the memory they own (check RAII idiom).
In this particular case, std::vector
would provide all such features: heap-allocated data, use of initializer-list (like {1, 2, 3}
), handlers and move semantics among other features.
For stack-allocated arrays you can consider std::array
, should you need them.
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]);
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