Reputation: 217
I feel that I am extremely close to getting this correct, but I am missing out on a vital point of calling the print function in my main method. I am a bit out of practice so simply a push in the right direction would help. My code is supposed to print out the 2D array in row major fashion, followed by column major fashion.
// ArrayPointer.c
#include <stdio.h>
#include <math.h>
// a: array pointer, m: # of rows, n: # of columns
void printMatrixRowMajor(int *a, int m, int n){
printf("Matrix row major fashion:\n");
int x[3][4];
a = &(x[0][0]);
for (m=0;m<3;m++){
for (n=0;n<4;n++){
printf("%d ", *(a + (m*4)+n));
}
printf("\n");
}
}
// a: array pointer, m: # of rows, n: # of columns
void printMatrixColMajor(int *a, int m, int n){
printf("\nMatrix column major fashion:\n");
int x[3][4];
a = &(x[0][0]);
for (n=0;n<4;n++){
for (m=0;m<3;m++){
printf("%d ", *(a + x[m][n]));
}
printf("\n");
}
}
main()
{
int row, col;
int x[3][4], *xptr;
xptr = &(x[0][0]);
printf("%d", printMatrixRowMajor);
}
Upvotes: 1
Views: 270
Reputation: 27126
Your slightly modified code could look like this:
#include <stdio.h>
#include <math.h>
// a: array pointer, m: # of rows, n: # of columns
void printMatrixRowMajor(int *a, int m, int n) {
printf("Matrix row major fashion:\n");
for (int y = 0; y < m; y++) {
for (int x = 0; x < n; x++) {
printf("%d ", *(a + (y * n) + x));
}
printf("\n");
}
}
int main() {
int x[3][4] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
printMatrixRowMajor(x, 3, 4);
return 0;
}
Changes
Output in Console
If you run the program it gives the following output on the console:
Matrix row major fashion:
1 2 3 4
5 6 7 8
9 10 11 12
Upvotes: 3