Thursday, July 30, 2009

Passing 2-d arrays in C++?

I'm getting an error when I try to compile this in Dev C++, and I still can't seem to figure out what's wrong.





"invalid conversion from `char (*)[((unsigned int)((int)n))]' to `char' "





The code below is just the basic stuff; assume I did everything correctly where my comments are. Could anyone tell me how to properly pass a two-dimensional character array to another function? Thanks!





#include %26lt;iostream%26gt;


using namespace std;





void funcOne(char,int,int);





int main()


{


int m,n;


//statements to define m and n





char arr[m][n];


//statements to populate array





funcOne(funcOne,m,n); // ***error is here***


return 0;


}





void funcOne(char arr[][],int m,int n)


{


// things to do


}

Passing 2-d arrays in C++?
Your prototype shows funcOne as taking a char, not a char[ ][ ]


In any event it is considered bad form to actually try to pass an array (if the compiler supprts it then the whole array must be copied onto the stack), instead you want to pass a reference or pointer to a 2 dimensional array; out of laziness I'd just pass a pointer to the first element of the array, so the prototype becomes:


void funcOne( char * arrayStart, int nRows, int nCols);





Before you can allocate your array, you'll need to set m %26amp; n:


int m=3;


int n=4;


char arr[m][n];





now you can pass it in:


funcOne( %26amp; arr[0][0], m, n);


Note we're passing the address (%26amp;) of arr[0][0], which is the address of a char, that should work.





Now funcOne's return and passed types MUST match the profile, so it becomes


void funcOne( char * arrayStart, int numRows, int numCols)


{


// work with *arrayStart, arrayStart[1] and so on.


// Note that you can only use 1 dimension


// for the array subscipt,


// you can convert a row, column to


// arrayStart[column + row * numCols]


// so 0,0 maps to the first element,


// 0-numRows, 0 maps to the first 0 through numRows


// second row (row=1, since we're 0 based)


// starts at arrayStart[numCols]


// and so on





}


No comments:

Post a Comment