2

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];*

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    this shouldnt be too surprising, c and c++ are differrent langauges. The code will also not compile as fortran – 463035818_is_not_an_ai Nov 23 '19 at 11:15
  • C++ is not a superset of C. There are things in C that are not valid C++ (like eg VLA as in the question); there are things in C that have a different meaning in C++ (like eg `sizeof '$'` means `sizeof (int)` in C but `sizeof (char)` in C++). – pmg Nov 23 '19 at 11:28

1 Answers1

2

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • The advice is good, but here it seems that the problem is not the VLA declaration by itself, accepted by most compilers, but the fact that in C++ you don't have a simple and clean way to pass them as argument of a function. Another strong reason not to use them – Damien Nov 23 '19 at 11:45