Printing char[][] in a function

Hi,
let's say we have declared
1
2
char matrix[3][4];
int x, y;

and then we do printout:

1
2
3
4
5
6
7
8
9
for(x = 0; x < 3; x++)
        {
            for(y = 0; y < 4; y++)
            {
                printf("%c", matrix[x][y]);
            }
            printf("\n");
        }
        printf("\n");*/


How would I create a function and what would the arguments be to print this from function?
1
2
3
4
5
6
7
8

printMat(/*insert whatever needed*/);


void printMat(/*insert whatever needed*/)
{

}
That all depends on the broader context of your program.
If matrix is global (should be avoided), then printMat doesn't really need any arguments.

Line 2: If this is supposed to be a function prototype, the return type must match the implementation: void.

It's better style to pass matrix as an argument.
1
2
3
void printMat (char matrix[][4])
{  // code as in second snippet
}


You can also extend the arguments to pass the dimensions of the matrix. This makes your for loops somewhat more generic.
1
2
3
4
5
6
7
8
9
void printMat (char matrix[][4],int rows, int cols)
{  for (int x = 0; x < rows; x++)
    {  for (int y = 0; y < cols; y++)
        {  printf("%c", matrix[x][y]);
        }
        printf("\n");
    }
    printf("\n");*/
}


However, because this is a 2 dimensional array, the second dimension dimension of the matrix must be specified in the first argument making the print routine somewhat less generic. There are ways around that, but those are beyond the scope of your question.
Last edited on
matrix is not global, its declared in main...

There is no way I could do something like?
 
void printMat (char matrix[][],int rows, int cols)


And pass it with some pointers or something?


I don't know if dimensions of matrix will always be 3,4. Thats why they have to be passed separately)
Last edited on
You could use a c++11 array of arrays (or vector of vectors) & query the size in your function.

1
2
3
4
5
6
7
8
9
void printMat(const std::array<std::array<char>> &matrix)
{
   unsigned int xsize = matrix.size();
   if(xsize>0)
   {
      unsigned int ysize = matrix[0].size();

      for(unsigned int x = 0 ; x < xsize ; x++)
      // etc... 
Last edited on
Topic archived. No new replies allowed.