### How to dynamic assign a global 2d array in C++

0

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*;

void setArray(double x, double y, double z){
array = new double*;
array = x;
array = 0;
array = 0;
...
``````

if there any method I can set a 2d array directly using values {{x,0,0},{0,y,0},{0,0,z}}?

2012-04-04 02:18
by Danny Su

1

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; // OK
``````

Fill them with copying:

``````void setArray(double x, double y, double z){
double temp = {{x,0,0},
{0,y,0},
{0,0,z}};
memcpy(&array, &temp, sizeof(array));
}
``````
2012-04-04 06:11
by anatolyg

-1

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;
``````

However, if you want to use an initialisation list, you could do it like this:

``````typedef double Array;

Array& array(double x = 0.0, double y = 0.0, double z = 0.0) {
static double array_ = {{x,0,0},{0,y,0},{0,0,z}};
return array_;
}

// init:
array(4,5,8);
// access:
array()[0,2];
``````
2012-04-04 02:22
@anatolyg: Yes, thanks. I removed the `static` keyword by accident. Fixed now - bitmask 2012-04-04 06:41
@JonasByström: Yes, the variable was intended to be `static`, but I forgot the most important keyword when typing the example - bitmask 2012-04-04 06:43
@bitmask `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