Monday, May 24, 2010

Problem with Matrix C++?

I'm trying to call a function where I can set up a Matrix. At the start, I set up the function:


void setmatrix(double a[x][y], char b)


{


int i, j;


printf("Enter values for Matrix %c:\n", b);


for (i=0; i%26lt;=x; i++)


{


for (j=0; j%26lt;=y; j++)


{


printf("Row %d, Column %d: ", i+1, j+1);


scanf("%lf", %26amp;a[i][j]);


}


}





Now, I get the user to input the amount of rows and columns which are x and y respectively. My problem is trying to call the function and what to put inside. I tried setmatrix(a[x][y], b). In my main function, I declared integers for x and y, character for b, and double a[3][3] (I needed an initial matrix).

Problem with Matrix C++?
The funny thing is that in certain OTHER programming languages, what you are doing would work. :-)





For C++, arrays do NOT have size information associated with them.





setmatrix(a[x][y], b) is actually setmatrix(double, char). The "a[x][y]" is called a _dereference_ and is getting a single value from your array.





You need:





double myMatrix[3][3];


char myMatrixName;





setmatrix(a, 3, 3, %26amp;myMatrixName);





void setmatrix(double a[][3], int x, int y, char *b) {


...


}





myMatrix == a pointer to an array of pointers.


myMatrix[0] == a pointer to the first ROW of values


myMatrix[0][0] = The actual value in the first column.





For your declaration, you NEED to declare the parameter as [][3]. If you want to create variably sized matrices, you'll have to look at arrays of pointers or (better yet) creating a single dimension array and figure out how to map [x][y] to a single array index. :-)





Passing arrays in C and C++ is ugly and has always been a source of confusion (which is why Java decided to make 2-D arrays a real pain in the [butt], but less confusing)





I'd recommend searching the web for C++ matrix libraries and see how they implement the data structure. Usually they create a Matrix class in order to side-step the whole problem of passing a 2-D array.


No comments:

Post a Comment