0

I am passing a two dimensional array to the mark function.

void mark(int n, int m, int i, int j, int canvisit[][m], int a[][m]){}

this code is working perfectly in C on Codeblocks but in C++, I am getting errors like :

prog.cpp:9:55: error: use of parameter outside function body before ']' token
 void mark(int n, int m, int i, int j, int canvisit[][m], int a[][m]){
                                                       ^
prog.cpp:9:56: error: expected ')' before ',' token
 void mark(int n, int m, int i, int j, int canvisit[][m], int a[][m]){
                                                        ^
prog.cpp:9:58: error: expected unqualified-id before 'int'
 void mark(int n, int m, int i, int j, int canvisit[][m], int a[][m]){

Am I doing something wrong here? I am giving the number of columns before by int m , and this is working in C but not C++. Any help will be highly appreciated.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
tarunkt
  • 306
  • 2
  • 12

2 Answers2

3

The array arguments you declare are variable-length arrays and those are not allowed in C++. You have to solve in in other ways, like using templates, std::vector or std::array.

Remember that C and C++ are two very different languages. C++ may have been originally developed from C, and they share syntax for many things, but they are still different languages with different rules.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

Only C supports variable length arrays, C++ doesn't. C++ standard says that the size of the array must be a constant expression.

Use std::vector instead. Declaration should be

void mark(int n, int m, int i, int j, vector< vector<int> > &canvisit, vector< vector<int> > &a);
haccks
  • 104,019
  • 25
  • 176
  • 264
  • Thanks. Can you please tell me then how I should approach my problem ? – tarunkt Nov 15 '15 at 09:38
  • 1
    As stated, C has some (very few) new constructs that are not supported by C++. Originally, ANSI C 89 is very close to a true subset of C++. For example, in the K&R book (ANSI version) all examples compile with a C++ compiler too. Since C99, the languages have diverged somewhat. In C++, you use std::vector as the main workhorse, sometimes you can use std::array for fixed-length arrays. In general, use the STL (vector, map, list, algorithms, iterators...) it is an amazingly fast and versatile part of the standard library! – Erik Alapää Nov 15 '15 at 09:46
  • @tarunkt; Edited the answer. – haccks Nov 15 '15 at 09:48