simplest
simplest

Reputation: 217

Printing a 2D print function in C

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

Answers (1)

Stephan Schlecht
Stephan Schlecht

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

  • in main there is some matrix data defined
  • printMatrixRowMajor is called (not printf of a function pointer)
  • two index variables are used to traverse the matrix elements in printMatrixRowMajor
  • the dimensions of the matrix is used to visit the matrix elements
  • the main function signature adopted
  • return 0 added to main

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

Related Questions