How can I assign an array from an initializer list? How can I assign an array from an initializer list? arrays arrays

How can I assign an array from an initializer list?


You cannot assign directly to an array after its declaration. Basically your code is the same as

int main(){    double arr[2][2];    arr = { {1, 2}, {3, 4.5} }; // error}

You have to either assign the value at declaration

double arr[2][2] = { {1, 2}, {3, 4.5} };

or use a loop (or std::copy) to assign elements. Since your array seems to be a member variable, you can also initialize it in the constructor initialization list:

 mcmc_dhs() : data(), cosmohandler(0.3,0.7,0.21,0.8,0.04),               lenseff(), intrvar(),               boundaries{{0,512},{0,512},{0.01,5.},{100.,3000.},{0.1,50}} {     // rest of ctor implementation }


When you said

boundaries = {{0,512},{0,512},{0.01,5.},{100.,3000.},{0.1,50}};

it was incorrect, because C++ does not let you reassign array values. There is an easy workaround, but it is somewhat tedious. All you have to do is assign the values one by one.

For example:

boundaries[0][0] = 0;boundaries[0][1] = 512;boundaries[1][0] = 0;boundaries[1][1] = 512;

and so on. I had this same problem in an Arduino program.


Array are essentially just pointers. C++ (being a symbol based programming language) has its own interpretations for arrays. Meaning:

int* a[3]; you've declared the array, but currently the values assigned to each element is some junk values that were already stored at the memory location allotted to your array.

a={1,2,3}; won't work because: C++ treat the array name 'a' as a pointer pointing at the address location of the 1st element in array. 'a' is basically interpreted by C++ as '&a[0]' which is the address of the element a[0]

So, you have 2 ways to go about assigning values

  1. using array indexing (your only option if you don't know what pointers are)

    int a[3];for(int i=0;i<3;++i) // using for loop to assign every element a value{cin>>a[i];}

2 treating it as a pointer and using pointer operation

    int a[3];    for(int i=0;i<3;++i) // using for loop to assign every element a value    {    cin>>*(a+i); // store value to whatever it points at starting at (a+0) upto (a+2)    }

Note: can't use ++a pointer operation as ++ changes the position of a pointer whereas a+i will not change the location of pointer 'a', and anyways using ++ will give a compiler error.

Recommend reading Stephen Davis C++ for dummies book.