'Passing an array in struct initialization

I would like to create a struct which contains both an int and an array of int. So I define it like

struct my_struct {
int N ;
int arr[30] ;
int arr[30][30] ;
}

Then I would like to initialize it with an array which I have already defined and initialized, for example

int my_arr[30] ;
for (int i = 0; i < 30; ++i)
{
my_arr[i] = i ;
}

Then I thought I could initialize a struct as

my_struct A = {30,my_arr}

but it doesn't seem to work (gives conversion error). P.s. and how would it work with a 2d array?



Solution 1:[1]

Arrays cannot be copy-initialised. This isn't particular to the array being member of a class; same can be reproduced like this:

int a[30] = {};
int b[30] = a; // ill-formed

You can initialise array elements like this:

my_struct A = {30, {my_arr[0], my_arr[1], my_arr[2], //...

But that's not always very convenient. Alternatively, you can assign the array values using a loop like you did initially. You don't have to write the loop either, there's a standard algorithm for this called std::copy.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 eerorika