Ok so here's my problem... I know this code works for a pointer of a 2Darray inside the same function, but when I try to do the same for a 2D array pointer passed by reference it obviously won't work... any help??
Ok so here's my problem... I know this code works for a pointer of a 2Darray inside the same function, but when I try to do the same for a 2D array pointer passed by reference it obviously won't work... any help??
the | after the < sign in the for loop is just my cursor, ignore.
Can you just copy the code instead of posting a screenshot, I can hardly read that crap since it's so dark.
Code:/************************************************************************************ print_matrix(): This will print the contents of the matrix M which has r rows and c columns. The matrix will be printed one row per line. Each row will be printed between pipe characters('|'). Each element of the vector will have a field width of 8 and each element will be left aligned within that field. ************************************************************************************/ void print_matrix(int *M, int r, int c) { int (*p)[c], i; for ( p = M; p < &M[r]; p++ ) { printf("\n|"); for ( i = 0; i < c; ++i) { printf("%d", (*p)[i]); if ( i == (c-1)) printf("|"); } } printf("\n"); }
You will have to pass in the 2d array and give its dementions. Your declaration is off.
Code:void print_matrix(int **M, int width, int length)
There are a few other ways to accomplish this.
Your array traversal logic would be correct if M were an int **. However, since M is an int *, your row "pointer" must increment by c elements each time, assuming row major ordering.
thanks. I solved it with this:
the output is ........ty, but that's what my professor wants.. i guess i could improve it without it hurting my grade but i ahve to turn it in in an hour and i have one more method to work on...Code:void print_matrix(int *M, int r, int c) { int i, j, k=0; for ( i = 0; i < r; ++i ) { printf("\n|"); for ( j = 0; j < c; ++j) { printf("%d\t", M[k++]); if ( j == (c-1)) printf("|"); } } printf("\n"); }