J
J
Jolek2020-12-10 00:22:42
C++ / C#
Jolek, 2020-12-10 00:22:42

How to use a function to print a two-dimensional array?

Why does it display only the first line and the rest is something incomprehensible?

#include <stdio.h>
#include <stdlib.h>

 int print_arr(int str, int stlb, int matr[][stlb]){
 	int k, i;
 	for(k = 0; k < str; k++){
    for(i = 0; i < stlb; i++){
    printf("%d\t", matr[k][i]);
  }
    printf("\n");	
}
}

int  main()
{
  int L = 0, N = 0, k, i;
    int mass[10][10];
    scanf("%d", &N);
    L=N;
    for(k = 0; k < N; k++){
    printf("[%d]\n", k);
    for(i = 0; i < L; i++){
    	scanf("%d", &mass[k][i]);
  }
}
    printf("matrix NxN\n");
    print_arr(N, L, &mass[k][i]);
  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2020-12-10
@jcmvbkbc

Why does it display only the first line and the rest is something incomprehensible?
int print_arr(int str, int stlb, int matr[][stlb]){
...
}

int mass[10][10];
...
print_arr(N, L, &mass[k][i]);


There are two mistakes here:
- firstly, you promised that you would pass an array to print_arr, the last dimension of which is equal to the second parameter of the function, and you pass an array, the second dimension of which is 10 and does not depend on the second parameter in any way
- secondly, instead of an array, you pass the address element that you didn't even complete.
If you already decided to use VLA, then do it sequentially, for example like this:
int  main()
{
    int L = 0, N = 0, k, i;
    scanf("%d", &N);
    L=N;
    int mass[N][L];
    for(k = 0; k < N; k++){
        printf("[%d]\n", k);
        for(i = 0; i < L; i++){
    	    scanf("%d", &mass[k][i]);
        }
    }
    printf("matrix NxN\n");
    print_arr(N, L, mass);
    return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question