# Help regarding 2D array as parameter

``````#include<bits/stdc++.h>
using namespace std;
void p(int arr[][n], int m, int n)
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
cout<<arr[i][j]<<" ";
}
}
int main()
{
int t;
cin>>t;
while(t--)
{
int m, n;;
cin>>m>>n;
int a[m][n];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
cin>>a[i][j];
}
p(a,m,n);
cout<<endl;
}
return 0;
}
``````

I encountered a strange error while trying to pass 2d array in a function. What might be the cause of the error? If any syntax issue is there, please let me know!
Error:

prog.cpp:3:18: error: ‘n’ was not declared in this scope
void p(int arr[][n], int m, int n)
^
prog.cpp:3:20: error: expected ‘)’ before ‘,’ token
void p(int arr[][n], int m, int n)
^
prog.cpp:3:22: error: expected unqualified-id before ‘int’
void p(int arr[][n], int m, int n)
^

You can not pass array like this in function fun(arr[][n],int n). 2D array must have fixed size of column.

1 Like

@sebastian So what to do in this case where the column size varies by test cases!?

you can use vectors also

3 Likes

Yeah but w/o vectors i wanna use 2d array and also column size varies from tc to tc…then? @deepasnhu_1729

Pass 2D array of max size to the function like fun(arr[],int rint c). But I think this will not work for larger size.

How to pass a 2D array as a parameter in C? - GeeksforGeeks See this or use vectors

I guess you should use vector, vector’s are designed for time like these only. Isn’t it.
In 2d array your compiler has to know before hand the size of array because how array is stored internally. So in any way you need to give information about column(CONSTANT) to compilers.
So your work can be done by vectors easily.

1 Like

ok bro @deepasnhu_1729

@sebastian after adding 1000 to column size in parameter, getting this single error:

prog.cpp: In function ‘int main()’:
prog.cpp:25:16: error: cannot convert ‘int ()[n]’ to ‘int ()’ for argument ‘1’ to ‘void p(int (*), int, int)’
p(a,m,n);
^

You can use dynamic allocation, it will work.
For eg in 1D array you pass as: void print(int* a);
In 2D array:

1. Create a 2D dynamic array;
2. Pass it as: void print(int **a)

ok will try this @pranshugupta

In main also you have to define like arr[m].