0

I've looked at other posts regarding to this problem but can't really seem to apply it to my situation particularly this post: Passing a 2D array to a C++ function

int compute(int size, int graph[][size], int u, int v)

and get the following error:

candidate function not viable: no known conversion from
  'int [size][size]' to 'int (*)[size]' for 2nd argument
int compute(int size, int graph[][size], int u, int v)

When I call this function in my main method I do it the following way:

compute(size,matrix,0,size-1)

Any suggestions as what my problem is?

Community
  • 1
  • 1

2 Answers2

1
template<size_t sizex, size_t sizey>
int compute(int (&graph)[sizex][sizey], int u, int v);

This behaves the way people expect, for example sizeof returns the correct size without needing to worry about tricky pointer conversions. It will also only let you pass 2d-Arrays, not pointers.

keltar
  • 15,618
  • 2
  • 31
  • 40
nwp
  • 8,897
  • 2
  • 32
  • 67
  • @Bathsheba In a way, yes. It is to date not possible in C++ to have variable length arrays so it is not possible to pass arrays that do not have fixed compile time sizes to this function. If VLAs were supported this may break. As of C++14 this will work with any 2D-Array. – nwp Apr 01 '14 at 13:23
  • So, consider yourself having a forward contract on an upvote for C++14 expiry, settled immediately. – Bathsheba Apr 01 '14 at 13:24
  • @Bathsheba I did not really understand your comment. Are you saying I should not use this code because it may break in a future version of C++? – nwp Apr 02 '14 at 08:59
1

The following worked for me on g++

const int SIZE=3;
int compute(int s, int graph[][SIZE], int u, int v) {
        return 0;
}


int main(int argc,char **argv) {
    int matrix[SIZE][SIZE];
    compute(SIZE,matrix,0,SIZE-1);
}

Note that SIZE is an integer constant, and is not to be confused with the first parameter of compute.

jsantander
  • 4,676
  • 12
  • 24