I initialize the array in the structure directly:

struct Array { int arr3[3]; }; Array ar = { 1, 2, 3}; 

how to initialize ar with an already created array

  int as[3] = { 1, 2, 3 }; Array ar = ->?as?<- ; 
  • Can pointers be used with your program logic? Those. instead of int arr3[3]; write int* arr3; and then assign it a pointer to the array created and initialized separately. - Andrey Kuruljov
  • There is no logic, just interest to reduce the expression 'Array ar = {as [0], as [1], as [2]};' readable for example `Array ar = & as;` - Vint

2 answers 2

What you use in the example is called an aggregate initialization (see clause 8.5.1. Of the Standard).

To initialize an Array already created array, you can write this:

 int a[3] = { 1, 2, 3 }; Array ar = { a[0], a[1], a[2] }; 

This is not very expressive, but it does not require changing the Array class. If you add a constructor, you can make initialization more beautiful (however, the class will no longer be trivial, and aggregate initialization will not be possible):

 struct Array { int arr3[3]; Array( int(&a)[3] ) : arr3 { a[0], a[1], a[2] } {} // добавили конструктор }; int a[] = { 1, 2, 3 }; Array ar = a; // теперь это работает Array ar2 = { 1, 2, 3 }; // а это перестало работать 

To ensure at the same time the possibility of initialization as in the original example, you will have to add another constructor:

 Array( int a0, int a1, int a2 ) : arr3 { a0, a1, a2 } {} 

    There is a clever way :) - if these arrays, like yours, are hidden in structures.

    In this case , the copy constructor is called [by default, if you have not defined your own]. So that

     struct Array { int a[3]; }; Array a = {1, 2, 3}; Array b = a; 

    will work. In the case of simple arrays, you need to copy.

    • And if in the structure some other data? Or two arrays? Then, too, need to copy? - Andrei Kurulyov
    • Alas, the default constructor does exactly that - it copies all the member data. - Harry