I want to make a 2d, 3 by 3 ,array like this:
double *array;
void setArray(double x, double y, double z){
array = {{x,0,0},
{0,y,0},
{0,0,z}};
}
I read some posts suggested something like this:
double **array = new double*[3];
void setArray(double x, double y, double z){
array[0] = new double*[3];
array[0][0] = x;
array[0][1] = 0;
array[0][2] = 0;
...
if there any method I can set a 2d array directly using values {{x,0,0},{0,y,0},{0,0,z}}?
Thanks in advance.
If you want to use lists like {{x,0,0},{0,y,0},{0,0,z}}
, you should use arrays with hard-coded size:
double *array; // no good
double array[3][3]; // OK
Fill them with copying:
void setArray(double x, double y, double z){
double temp[3][3] = {{x,0,0},
{0,y,0},
{0,0,z}};
memcpy(&array, &temp, sizeof(array));
}
If you don't need jagged array, and the size is known at design time you can use this syntax to declare it:
double array[3][3];
However, if you want to use an initialisation list, you could do it like this:
typedef double Array[3][3];
Array& array(double x = 0.0, double y = 0.0, double z = 0.0) {
static double array_[3][3] = {{x,0,0},{0,y,0},{0,0,z}};
return array_;
}
// init:
array(4,5,8);
// access:
array()[0,2];
static
keyword by accident. Fixed now - bitmask 2012-04-04 06:41
static
, but I forgot the most important keyword when typing the example - bitmask 2012-04-04 06:43
static
is not good either: the initialization will happen only once for static variables, so the function will work wrong the second time it's calle - anatolyg 2012-04-04 07:10