1
#include<stdio.h>

void print(int r, int c, int Ar[][c])
{
    int i,j;
    printf("\n");
    for(i=0;i<r;i++)
    {
        for(j=0;j<c;j++)
        printf("%d ",Ar[i][j]);
        printf("\n");
    }
}

int main()
{
  int m,n,i,j;
  int A[100][100];
 
  printf("Enter number of rows and columns matrix: ");
  scanf("%d%d", &m, &n);
  printf("Enter elements of first matrix:\n");
  for (i=0;i<m;i++)
  {
    for (j=0;j<n;j++)
    scanf("%d",&A[i][j]);
  }
  print(m,n,A);
  return 0;
}

Output: Enter number of rows and columns matrix:2 3 Enter elements of first matrix: 2 1 3 5 4 6

2 1 3 0 0 0

Why it's not printing the second line ?

3

2 Answers 2

0

EDIT: This question was tagged C++ before . . .


If you want to pass a plain old C-array to a function, you have 2 possibilities.

  1. Pass by reference
  2. Pass by pointer

What you used, does not even compile.

In C++ arrays must have a compile-time-known size.

Please see:

void function1(int(&m)[3][4])   // For passing array by reference
{}
void function2(int(*m)[3][4])   // For passing array by pointer
{}

int main()
{
    int matrix[3][4]; // Define 2 dimensional array

    function1(matrix);  // Call by reference
    function2(&matrix); // Call via pointer 
    return 0;
}

In any case. Usage of modern c++ containers like std::array or std::vector are nearly always the by far better solution.

Sign up to request clarification or add additional context in comments.

Comments

0

The following program works only if your compiler is C99 compatible.

#include <stdio.h>
 
// n must be passed before the 2D array
void print(int m, int n, int arr[][n])
{
    int i, j;
    for (i = 0; i < m; i++)
      for (j = 0; j < n; j++)
        printf("%d ", arr[i][j]);
}
 
int main()
{
    int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int m = 3, n = 3;
    print(m, n, arr);
    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.