Reputation: 11012
There is that way to set elements on array - int rgArrayNum [] = {16, 2, 77, 40, 12071};
How can I do same way on pointer with new ? I tried int *pArrayNum = new [] = {4 ,3 ,3} ;
but it didn't worked .
Upvotes: 0
Views: 98
Reputation: 157334
In c++11, you can write:
int *pArrayNum = new int[3]{4, 3, 3};
However, in c++03 array new initialization is not allowed; you'd have to initialize the members individually or by copy from an array on the stack:
int rgArrayNum [] = {16, 2, 77, 40, 12071};
int *pArrayNum = new int[sizeof rgArrayNum / sizeof rgArrayNum[0]];
std::copy(&rgArrayNum[0], &rgArrayNum[sizeof rgArrayNum / sizeof rgArrayNum[0]],
pArrayNum);
Upvotes: 7
Reputation: 397
You have to create the array not with integers but with integer pointers.
int* rgArrayNum2 [] = {new int(16), new int(16), new int(16), new int(16), new int(16)};
//test
int* test = rgArrayNum2[2];
*test = 15;
now rgArrayNum2[2] is 15.
Upvotes: 0
Reputation: 254431
In C++03 and earlier, you can't initialise the values of a dynamic array to anything except zero.
You can achieve something similar in C++11:
int *pArrayNum = new int [3] {4, 3, 3};
or if you don't mind using a container to manage the memory for you:
std::vector<int> array = {4, 3, 3};
Upvotes: 3