Reputation: 31
I tried same program for C & C++ i.e. passing 2D array to a function. The following program is working in C, but not working in C++, Please explain why so ?
IN C
#include<stdio.h>
void pass(int n, int arr[][n]) // or void pass(int n, int (*arr)[n])
{
printf("%d",arr[0][0]);
//.....
}
int main()
{
int n;
scanf("%d",&n);
int arr[n][n];
arr[0][0]=0;
pass(n,arr);
return 0;
}
IN C++
#include <bits/stdc++.h>
using namespace std;
void pass(int n, int arr[][n]) // or void pass(int n, int (*arr)[n])
{
cout << arr[0][0];
//.....
}
int main()
{
int n;
cin >> n;
int arr[n][n];
arr[0][0]=0;
pass(n,arr);
return 0;
}
3:29:error: use of parameter outside function body before ']' token void pass(int n, int arr[][n]) // or void pass(int n, int (*arr)[n])
6:9:error: 'arr' was not declared in this scope cout << arr[0][0];*
Upvotes: 2
Views: 129
Reputation: 310980
These statements
int n;
scanf("%d",&n);
int arr[n][n];
provide a declaration of a variable length array. A variable length array is an array dimensions of which depend on run-time values. It is a feature of C that compilers may conditionally support.
In C++ there is no such a standard feature. So the C++ compiler issues an error. In C++ dimensions of an array shall be compile-time constants. Though some C++ compilers can have their own C++ language extensions that can include the feature of variable length arrays.
In C++ use the class template std::vector
instead of variable length arrays.
Upvotes: 2