C++ Initialize array pointer

Viewed 34879

How do I initialize a pointer to a literal array?
I want *grid to point to the new allocated int array {1, 2, 3}.

int *grid = new int[3];
*grid = {1, 2, 3};

thank you.

4 Answers

I'm not sure if this is obvious but you can do this in one line.

int *grid = new int[3] {1, 2, 3};

Since this is C++ we are talking about you can also split it into two files. Where your .h file contains:

int *grid;

And your .cpp file contains:

grid = new int[3] {1, 2, 3};
Related