1

Following code runs fine -

void func(int m[][2])
{
    cout<<(m[0][0])<<endl;
}

int main()
{
//    int x=2;
    int m[2][2];
    m[0][0] = m[0][1] = m[1][0] = m[1][1] = 5;
    cout<<m[0][0]<<endl;
    func(m);
}

But when I change main() as follows -

int main()
{
    int x=2;
    int m[x][x];
    m[0][0] = m[0][1] = m[1][0] = m[1][1] = 5;
    cout<<m[0][0]<<endl;
    func(m);
}

I get the error message -

try.cpp:16:11: error: cannot convert ‘int (*)[(((long unsigned int)(((long int)x) + -0x00000000000000001)) + 1)]’ to ‘int (*)[2]’ for argument ‘1’ to ‘void func(int (*)[2])’

Also, the following runs fine -

int main()
{
    int x=2;
    int m[x][x];
    m[0][0] = m[0][1] = m[1][0] = m[1][1] = 5;
    cout<<m[0][0]<<endl;
    //func(m);
}

Can anyone explain the issue here? Thanks.

theharshest
  • 7,767
  • 11
  • 41
  • 51

1 Answers1

1

Variable length arrays are not valid in C++. g++ allows this as an "extension".

int x=2;
int m[x][x];    //Illegal in C++

You should go for Dynamic Memory allocation if you want to dynamically allocate memory to an array.

int x=2;
int *m = new int[x];

It is better if you use STL :

int x = 10;
std::vector<int> m(n);

Or you can use const not a variable when creating it.

const int x=2;             //it's a compile time constant
int m[x][x];          
Shivam
  • 303
  • 4
  • 20
  • Alternatively you should recommend the OP to use [tag:c++] STL containers instead of 'raw' [tag:c] arrays, to overcome all the obstacles with managing memory allocation on your own. – πάντα ῥεῖ Nov 24 '13 at 04:34