2D arrays with C ++

I have a function that takes a pointer to a pointer as an argument.

func(double **arr, int i);

where in the main function the array is defined as follows:

double arr[][] = //some initialization here;

How can I call this function from my main code. I tried the following but it gave an error

func (&arr);

Does not work. Any help is appreciated. Thanks

+2
source share
3 answers

A double **pis not the same as double[][] a, therefore, you cannot transfer it to others.

, (!) , , [][]. , , . , , : .

+----+           +---------+---------+---------+
| (a---------->) | a[0][0] | a[0][1] | a[0][2] | ...
+----+           +---------+---------+---------+ 
                 | a[1][0] | a[1][2] | ...
                 +---------+---------+
                   ...

- , , .

+---+       +------+      +---------+---------+
| p-------->| p[0]------->| p[0][0] | p[0][3] | ...
+---+       +------+      +---------+---------+
            | p[1]--\    
            +------+ \    +---------+---------+
             ...      --->| p[1][0] | p[1][4] | ...
                          +---------+---------+

, .


. ( c, ).

+10

arr - double[X][Y] - X Y - X Y . , . , C, . , , (*) [Y] - Y . , , , . , double**.

- , - . :

void func(double* arr, int w) {
   // arr[2][3]
   arr[2*w + 3] = ...;
}


double x[6][8] = { ... };
func(&x[0][0], 8);

++, , ( ) , :

template <int W, int H>
inline void func(const double (&arr)[W][H]) {
  arr[2][3] = ...;
}

double x[6][8] = { ... };
func(x); // W and H are deduced automatically

, , , - (, new -, ). ++. :

#include <vector>

void func(std::vector<std::vector<double> > arr) {
  arr[2][3] = ...;
}

std::vector<std::vector<double> > x(6, std::vector<double>(8));
x[0][0] = ...;
...
func(x);

Boost, MultiArray:

void func(boost::multi_array<double, 2> arr) { // 2 means "2-dimensional"
  arr[2][3] = ...;
}

boost::multi_array<double, 2> x(boost::extents[6][8]);
x[0][0] = ...;
...
func(x);

[] , . , , , . :

double x1[8] = { 1, 2, ... };
double x2[8] = { 3, 4, ... };
...
double* x[6] = { x1, x2, ... };

func(x);
+16
func(double *arr[100])

You need to tell the compiler the size of the dimension so that it can create the correct address

  arr[y][x]

turns into

  arr[100*x+y]

If you define your function as func (double ** a), then you are pointing to an array of pointers by specifying dmckee

-1
source

Source: https://habr.com/ru/post/1726349/


All Articles