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 .
3 Answers
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);
3 Comments
Mike Seymour
You'll need a
[3] there; it won't infer the size from the initialiser list.URL87
@ecatmur: I tried your code and got error "no matching function for call to 'copy(int [5], int&, int*&)'" . I added #include <algorithm> . What I did not true ?
ecatmur
@URL87 I forgot a
& on the second parameter. Fixed.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};
3 Comments
R. Martinho Fernandes
While
vector is without a doubt the superior answer, you can actually do it without a container new int[3] { 4, 3, 3 };. I don't see why anyone would want to, though.Mike Seymour
@R.MartinhoFernandes: So you can. I've learnt something today.
URL87
@R.MartinhoFernandes: It wat only example .. I mean dynamic element's count .