0

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 .

0

3 Answers 3

7

In , you can write:

int *pArrayNum = new int[3]{4, 3, 3};

However, in 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);
Sign up to request clarification or add additional context in comments.

3 Comments

You'll need a [3] there; it won't infer the size from the initialiser list.
@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 ?
@URL87 I forgot a & on the second parameter. Fixed.
3

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

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.
@R.MartinhoFernandes: So you can. I've learnt something today.
@R.MartinhoFernandes: It wat only example .. I mean dynamic element's count .
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.