2D Array as Parameter w/ Unknown Size

Jan 25, 2012 at 12:43am
Is it possible to pass 2D arrays as a parameter without knowing the size? The effect I'm trying to get is:

void print(double a[][], int row, int col){//Print 2D array}

That way I can just make a method that works with different sizes. I was thinking of using pointers to get around needing to set a size, but I'm not sure how to go about it. So, is there a way to do this:

void print(double **a, int row, int col){//Print 2D array}

I'm trying to make a matrix class.
Last edited on Jan 25, 2012 at 12:45am
Jan 25, 2012 at 12:54am
Those two functions are in fact, identical. Arrays passed to functions are automatically converted to pointers. The method you are showing would be a standard way to handle an array passed as a parameter...though wouldn't you want this function to be a method of your matrix class, and have it print the internal array?
Jan 25, 2012 at 1:08am
Yeah, I had it implemented as a class method, but I just wanted to see if I can rewrite print just to test out pointers. I still can't seem to get it to work. If I use the second function, it doesn't work with my 2D array.

1
2
double A[2][2] = {{1, 2}, {2, 3}}
print(A, 2, 2);


It gives me an error. "cannot convert parameter 1 from 'double [2][2]' to 'double **"
Jan 25, 2012 at 1:10am
pass in (&A,2,2) instead
Jan 25, 2012 at 1:14am
If I use (&A, 2, 2) I get: "cannot convert parameter 1 from 'double (*)[2][2]' to 'double **'"
Last edited on Jan 25, 2012 at 1:15am
Jan 25, 2012 at 1:46am
You can't convert the 2D array to a double**. It's a common misconception.

To pass the 2D array you have to at least specify the second size.
void print(double a[][2], int rows){}

Another way is to use templates
1
2
template <int ROWS, int COLS>
void print(double (&a)[ROWS][COLS]){} 
Last edited on Jan 25, 2012 at 1:47am
Jan 25, 2012 at 4:23pm
Ah, you are right. Would the row/col indexing be horrible cumbersome if you just passed a plain ol' pointer to double?
Jan 25, 2012 at 5:37pm
Using functions it would be better to define the maximum possible value your array could acquire... then pass the array
Last edited on Jan 25, 2012 at 5:59pm
Topic archived. No new replies allowed.