Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ dynamic array initialization with declaration

I have function like this:

void findScarf1(bool ** matrix, int m, int n, int radius, int connectivity); 

and in main function I create 2d dynamic array to pass in this function

    bool matrix[6][7] = {
    {0, 0, 1, 1, 1, 0, 0},
    {0, 0, 1, 1, 1, 0, 0},
    {0, 0, 1, 1, 1, 0, 0},
    {0, 0, 1, 1, 1, 0, 0},
    {0, 0, 1, 1, 1, 0, 0},
    {0, 0, 1, 1, 1, 0, 0}
};

The problem is:

findScarf1(matrix, 6, 7, 3, 4);

causes error C2664: 'findScarf1' : cannot convert parameter 1 from 'bool [6][7]' to 'bool **'

How to initialize array compactly(simultaneously with declaration)?

p.s. sorry if it's duplicate question but I've spent 1.5 hours figuring it out

like image 812
olha Avatar asked Jul 10 '13 09:07

olha


2 Answers

If you look at how your array is laid out in memory, and compare it how a pointer-to-pointer "matrix" is laid out, you will understand why you can't pass the matrix as a pointer to pointer.

You matrix is like this:

[ matrix[0][0] | matrix[0][1] | ... | matrix[0][6] | matrix[1][0] | matrix[1][1] | ... ]

A matrix in pointer-to-pointer is like this:

[ matrix[0] | matrix[1] | ... ]
  |           |
  |           v
  |           [ matrix[1][0] | matrix[1][1] | ... ]
  v
  [ matrix[0][0] | matrix[0][1] | ... ]

You can solve this by changing the function argument:

bool (*matrix)[7]

That makes the argument matrix a pointer to an array, which will work.


And by the way, the matrix variable you have is not dynamic, it's fully declared and initialized by the compiler, there's nothing dynamic about it.

like image 54
Some programmer dude Avatar answered Sep 20 '22 03:09

Some programmer dude


Technically, a 2D array is an array of 1D arrays. So it cannot convert into pointer to pointer. It can convert into pointer to array, though.

So this should work:

void findScarf1(bool (*matrix)[7], int m, int n, int radius, int connectivity); 

Here bool (*matrix)[7] declares a pointer to array of 7 bool.

Hope that helps.

like image 34
Nawaz Avatar answered Sep 18 '22 03:09

Nawaz