'I want to make a function in C that prints a 2D array
I know how to print a 2D array without using a function (using nested for loops), but how would I implement a fuction that prints it.
This is what I tried
int print_matrix(int arr[M][N])
{
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
printf("{%i}",arr[i][j]);
}
printf("\n");
}
}
Solution 1:[1]
You want this:
int print_matrix(int M, int N, int arr[M][N])
{
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
printf("{%i}",arr[i][j]);
}
printf("\n");
}
}
int main(int argc, char *argv[])
{
int N = 4;
int M = 4;
//...
int arr[M][N];
//...
print_matrix(M, N, arr);
}
Solution 2:[2]
you need to add int M, int N to the function:
int print_matrix(int M, int N, int arr[M][N])
{
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
printf("{%i}",arr[i][j]);
}
printf("\n");
}
}
how to call your fucntion:
int M = 5;
int N = 4;
//define your array
int arr[M][N];
print_matrix(M, N, arr)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jabberwocky |
| Solution 2 | Tal Folkman |
