Assigning Values to An Array After Declaration

c-cpp

Once an array has been declared, it is good to know less tedious way of assigning values to its members than the following:

iaMyArray[0]=8;
iaMyArray[1]=3;
iaMyArray[2]=4;
iaMyArray[3]=0;
iaMyArray[4]=0;
iaMyArray[5]=1;
iaMyArray[6]=8;
iaMyArray[7]=8;

You can initialize arrays on their declaration but when you want your array to be initialised differently according to various cases those could be determined just at runtime.

Assigning or initialising after declarartion cannot be done directly. There are, however different things that you can do there, starting from creation of a local array initialized with the aggregate initialization and then memcpy-ed over your array (valid only for POD types), or using higher level libraries like boost::assign.

int iaMyArray[8];

{
int iaTmpArray[8] = { 8, 3, 4, 0, 0, 1, 8, 8 }
if( sizeof(iaTmpArray)<=sizeof(iaMyArray) )
memcpy( iaMyArray, iaTmpArray, sizeof(iaTmpArray) ); 
}