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

Go To StackoverFlow.com

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*[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.

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[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));
}
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[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];
2012-04-04 02:22
by bitmask
Thanks for reply. but I got syntax error: "cannot convert frm double [3][3] to double ** , pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast - Danny Su 2012-04-04 03:26
@user1311686: Yes, sorry, that couldn't have worked. See my edit please. This is not really clean, but if you insist on using static arrays with initialisation lists, that depend on runtime values, this is as close as you're going to get. You should consider avoiding this static array - bitmask 2012-04-04 03:48
This function returns a reference to a local variable; this doesn't wor - anatolyg 2012-04-04 06:05
As @anatolyg already stated, the reason being that you're referring to a stack variable that gets wiped as soon as you leave the function (and that stack frame) - Jonas Byström 2012-04-04 06:14
@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
@anatolyg: No, that is absolutely intended. You initialise once, and later only access the variable - bitmask 2012-04-04 07:40
Ads