0

How can I initialize ptr dynamically with new:

int values1[4][2] = {{2,3},{-4,0},{3,-7},{2,2}};
int values2[4][2] = {{1,1},{-2,-3},{4,12},{-5,25}};
    
int (*ptr[2])[4][2] = {&values1,&values2};

I tried the following but I get a mistake:

int *ptr = new int[2*4*2]{&values1,&values2}; 
9
  • 1
    Unless you have a very good reason not to, you should use containers for this, and not c-style arrays: en.cppreference.com/w/cpp/container Commented Oct 1, 2020 at 19:23
  • I'm trying to use dynamic array... Commented Oct 1, 2020 at 19:24
  • Dynamic array: std::vector Commented Oct 1, 2020 at 19:25
  • I can't use vector either Commented Oct 1, 2020 at 19:25
  • Why? Are you learning C or C++? Commented Oct 1, 2020 at 19:26

2 Answers 2

0

A typedef can help with this kind of tricky code

int values1[4][2] = { { 2, 3 }, { -4, 0 }, { 3, -7 }, { 2, 2 } };
int values2[4][2] = { { 1, 1 }, { -2, -3 }, { 4, 12 }, { -5, 25 } };

typedef int(*xxx)[2];

int main()
{
    xxx* ptr = new xxx[2];
    ptr[0] = values1;
    ptr[1] = values2;
    return 0;
}

I honestly have no idea how you would write it without the xxx typedef

EDIT

This appears to be the correct non-typedef version

int(**ptr)[2] = new (int(*[2])[2]);

I'm not quite sure I believe it.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, although I'm trying to use new
@Melissa See edit. I'm working on a non-typedef version.
0

With all that said about containers, you can do this:

int (*ptr)[4][2];


ptr = new int[2][4][2]{{{2,3},{-4,0},{3,-7},{2,2}},{{1,1},{-2,-3},{4,12},{-5,25}}};

8 Comments

Thank you! Although, how can I call values1 and values2 instead of writing all the values into the {}? ptr = new int[2][4][2]{&values1,&values2} doesn't work
Also is this a dynamic array?
You can't write it like that, because the {} does magic here :)
oh ok, is there another way I could initialize with new without rewritting the values?
Dynamic in the sense that it's dynamically allocated. Not dynamic in the sense that it won't extend as you add new values.
|

Your Answer

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