-2

This is a valid code according to c99 standard and this code-snippet is running fine on gcc compiler.

#include <stdio.h>
void foo( int n, int m, int a[][m]){
    //do stuff
}

int main() {
        int n,
            m;
        scanf("%d %d", &n, &m);
        int a[n][m];
        foo(n, m, a);
        return 0;
}

But the equivalent C++ code is not running on g++ compiler.

#include <cstdio>
#include <iostream>
using namespace std;
void foo( int n, int m, int a[][m]){
         //do stuff
}

int main() {
       int n,
           m;
    cin >> n >> m;
    int a[n][m];
    foo(n, m, a);
    return 0;
}

I am getting the following error.

error: use of parameter outside function body before ‘]’ token
void foo( int n, int m, int a[][m]){

I cannot find the simple solution in C++ as it available in C for this problem.

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
  • Which C++ standard are you compiling with? More importantly, does this program HAVE to be written in C++? – Mason Watmough Aug 20 '16 at 16:41
  • 4
    Any reason you expect two different languages have the same features? – too honest for this site Aug 20 '16 at 16:41
  • 2
    if you use C++, why not using vectors? you won't believe how many users here have problems with C multi-dimensional arrays. – Jean-François Fabre Aug 20 '16 at 16:42
  • @Jean-FrançoisFabre: That's nonsense. VLAs work fine in C. Just use a modern, compliant compiler. – too honest for this site Aug 20 '16 at 16:43
  • @MasonWatmough C++11. I am a C programmer and learning C++ that's why i tend to write program in C++, in order to learn C++. – abhishek jaiswal Aug 20 '16 at 16:46
  • The error you get seems very clear. Your C++ compiler warns you that you try to do something that can not be compiled, I mean using a parameter to define another parameter... I suggest you to replace the 2nd 'm' with a constant value, or simply remove it. – Laurent H. Aug 20 '16 at 16:47
  • @Jean-FrançoisFabre so there is no solution available in C++ for this problem. – abhishek jaiswal Aug 20 '16 at 16:48
  • 2
    @abhishekjaiswal if you're trying to learn C++, check out [vectors](http://www.cplusplus.com/reference/vector/vector/). – Mason Watmough Aug 20 '16 at 16:48
  • @abhishekjaiswal you might want to look at : http://stackoverflow.com/questions/1887097/variable-length-arrays-in-c – Bettorun Aug 20 '16 at 16:50
  • @LaurentH. I tried to replace 2nd m with constant parameter but problem persist. – abhishek jaiswal Aug 20 '16 at 16:51
  • 3
    @abhishekjaiswal C++ is *not* C-with-classes, it's a different language, and the backwards compatibility only goes so far - variable length arrays, the thing you are trying to use, is one of the things that C++ does not include support for. If you want to actually learn C++, I encourage you to learn C++ rather than learning how to write C that the G++ compiler will accept. – kfsone Aug 20 '16 at 20:38
  • 1
    @Olaf I think it is because of the unfortunate naming of the language, C++. It could be... D, nobody expects D to be source compatible with C. Furthermore, the ++ there kinda indicates C++ should be enhanced/improved C, so it's kinda counter-intuitive it's missing features of C (which is fine of course in itself, since it's a different language, not a version of C). – hyde Aug 21 '16 at 06:15
  • 1
    @hyde: Strange. While it sometimes happens, most don't think C# is the same as C. And no, it is not that VLAs are a "missing feature", it just does not have this feature (which is _one_ reason to stick with C in my projects). And it is not just that both have different features, but they have different semantics for identical syntax&grammar, too. Just consider the `const` qualifier, then operator overloading (which is a questionable feature anyway). FYI: read the history, C++ started as a C preprocessor, so the similarity was well justified **that time**. – too honest for this site Aug 21 '16 at 13:47

2 Answers2

1

First of all, you must replace m in int a[][m] with some constant value, as you cannot use variables to define columns of arrays in function headers.

Second of all, you cannot declare arrays with variable size as you've done int a[n][m], you have to use constants here too.

But if you want to use variable size arrays, you can create the arrays dynamically.

int** a = new int*[n]; // It creates an array of pointers of size n

and then you can loop through this array of pointers to allocate an array of integers to each of the pointer.

for (int i = 0; i < n; i++){
    a[i] = new int[m];
}

this will create you a 2D array of integers dynamically. And to pass this array as argument to some function, you can use pointer to pointer.

void foo(int n, int m, int** a){
     // here use it just like you use an array.
}

And when you are done using the array, you have to de-allocate the dynamically allocated array.

for (int i = 0; i < n; i++){
    delete[] a[i];
    a[i] = 0;
}
delete[] a;
a = 0;

And if you don't like this method, you can always use vector class.

vector<vector<int>> a(n, vector<int>(m));

To pass a vector to a function.

void foo(const vector<vector<int>>& a){
    size_t n = a.size();
    size_t m = 0;
    if (n > 0)
        m = a[0].size();
    // do your work
}

When using vector, you don't have to worry about dynamic allocation or de-allocation, the vector class handles this kind of stuff itself.

Ahmad Khan
  • 2,655
  • 19
  • 25
  • In the vector of vectors example, `vector> a(n, vector(m));` No loop is required. And regarding final example, since VLA's, like regular arrays in C, are passed by first-element-address as their value, the logical synonymous action for passing the vector of vectors to `foo` would be by *reference*. As-written, it is by-value. – WhozCraig Aug 20 '16 at 18:16
0

enter image description here

A simple solution in C++ for this problem would be to use a 2D vector

vector <vector<int> > vecArray( 10, vector <int> (10) )

and pass it to the function by reference &vec2DArray.

#include <vector>
#include <iostream>
#include <iomanip>
using namespace std;


//  function to pass 2d vector array by reference &
void function( int n, int m,  vector <vector<int> > & vec2DArray ) {

    for (int y=0; y<10; y++ ){
        for (int x=0; x<10; x++  ){

            // perform some calculations
            vec2DArray[y][x] = (y+1) * (x+1) *m *n;

        }
    }
}


int main() {
    cout<<"function to pass 2d vector array by reference & \n\n";

    // create a 2D vector of dimension [10][10]
    vector <vector<int> > vec2DArray( 10, vector <int> (10) );
    int n=0, int m=0;

    // call function, pass 2d vector array  by reference &
    function( 1, 1, vec2DArray );

    // display calculation results
    for (int y=0; y<10; y++ ){
        for (int x=0; x<10; x++  ){

            // display vec2DArray
            cout << setfill(' ') << setw(2)<< vec2DArray[y][x] <<" ";
        }  
        cout<<"\n";
    }
    cout<<"\n";


cout<<"Press ANY key to close.\n\n";
cin.ignore(); cin.get();
return 0;
}
Software_Designer
  • 8,490
  • 3
  • 24
  • 28