-3
#include<iostream>

using namespace std;

void seed(int* matrixAddr, int n, int m);

void main()
{
  int n, m;
  cin >> n >> m;

  int matrix[n][m]; // DevC++ does not throw an error here, where VS does instead 

  seed(matrix, n, m);
}

void seed(int* matrixAddr, int n, int m) {}

Accessing matrix directly means referencing a memory address - in this case, to the first element of the two-dimensional array.

Apparently, though, the address cannot be passed as-is to the seed function, which accepts a pointer as its first argument.

Why does this happen? Should this not be allowed?

The error DevC++ throws is the following: [Error] cannot convert 'int (*)[m]' to 'int*' for argument '1' to 'void seed(int*, int, int)'

Johnny Bueti
  • 637
  • 1
  • 8
  • 27
  • 4
    Doesn't matter what error you get, in this context `int matrix[n][m]; ` is simply not valid C++. –  Oct 14 '17 at 19:05
  • Thank you, it makes sense as I thought. Our programming professor, however, suggests we use this initialisation method for multidimensional arrays. Is there any way to deal with this? – Johnny Bueti Oct 14 '17 at 19:07
  • Variable length arrays are not legal G++. – msc Oct 14 '17 at 19:08
  • 1
    " however, suggests we use this initialisation method for multidimensional arrays" There are many ways to deal with this, but I suggest you start by getting a new so-called "professor". –  Oct 14 '17 at 19:10
  • I wish I could, Neil, trust me. May I ask how could I deal with that kind of initialisation and the question's problem? – Johnny Bueti Oct 14 '17 at 19:11
  • 1
    Please try my code given below... It will work. Let u try in http://rextester.com/PULAXL63031 – Dr. X Oct 14 '17 at 19:18

1 Answers1

1
#include <iostream>
using namespace std;

void seed(int** matrixAddr, int n, int m);

int main()
{
  int rows, cols;
  int **matrix = NULL;
  cin >> rows >> cols;

  matrix = new int*[rows]; 
  for(int i = 0; i < rows; i++)
     matrix[i] = new int[cols];

  seed(matrix, rows, cols);
  return 0;
}

void seed(int** matrixAddr, int rows, int cols) {
    cout << "It is OK" ;
}

You can check from here http://rextester.com/PULAXL63031

Dr. X
  • 2,890
  • 2
  • 15
  • 37