2

Is there a way in c++ to fill an array allocated like this

int **a = new int[4][2];

so that it's filled with values in one line like this

int a [4][2] = {{2,3,4},{5,6,7}};
TemplateRex
  • 69,038
  • 19
  • 164
  • 304
Max Rahm
  • 684
  • 11
  • 25

3 Answers3

6

You can do it in C++11 with universal initialization notation:

int(*a)[2] = new int[2][2]{{1,2},{3,4}};
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
0

a vector of vectors would work, but only in C++11. I guess you'd have to give up C compatibility for that

#include <vector>

int main()
{
   std::vector<std::vector<int>> v = {{2,3,4},{5,6,7}};   
}
TemplateRex
  • 69,038
  • 19
  • 164
  • 304
0

Prefer std::array to C-style arrays if your compiler has adequate C++11 support:

#include <array>

int main()
{
    std::array<std::array<int,3>,3> v = {1,2,3,4,5,6,7,8,9};
}