I am trying to pass a 2d array to a function in c++. The problem is that its dimension is not universal constant. I take the dimension as an input from the user and then try to pass the array. Here is what i am doind:
/*
* boy.cpp
*
* Created on: 05-Oct-2014
* Author: pranjal
*/
#include<iostream>
#include<cstdlib>
using namespace std;
class Queue{
private:
int array[1000];
int front=0,rear=0;
public:
void enqueue(int data){
if(front!=(rear+1)%1000){
array[rear++]=data;
}
}
int dequeue(){
return array[front++];
}
bool isEmpty(){
if(front==rear)
return true;
else
return false;
}
};
class Graph{
public:
void input(int matrix[][],int num_h){ //this is where I am passing the matrix
int distance;
char ans;
for(int i=0;i<num_h;i++){
for(int j=0;j<num_h;j++)
matrix[i][j]=0;
}
for(int i=0;i<num_h;i++){
for(int j=i+1;j<num_h;j++){
cout<<"Is there route between houses "<<i<<" and "<<j<<": ";
cin>>ans;
if(ans=='y'){
cout<<"Enter the distance: ";
cin>>distance;
matrix[i][j]=matrix[j][i]=distance;
}
}
}
cout<<"The matrix is: \n";
for(int i=0;i<num_h;i++){
cout<<"\n";
for(int j=0;j<num_h;j++)
cout<<matrix[i][j]<<"\t";
}
}
};
int main(){
Graph g;
int num_h;
cout<<"Enter the number of houses: ";
cin>>num_h;
int matrix[num_h][num_h];
g.input(matrix,num_h); //this is where I get an error saying
// Invalid arguments ' Candidates are: void input(int (*)[],
// int) '
return 0;
}
Help much appreciated. Thank you.
Instead of passing the entire matrix, pass a pointer to the matrix. To do this effectively, you need to either treat the matrix as 2D, but manage it as a vector, or use a vector of vectors.
Considering the first case, you would:
and
to
and access the elements using
Problems in your code:
Problem 1
is not valid C++. In a multi-dimensional array, all but the first dimension must be constants. A valid declaration would be:
Problem 2
is not valid C++. VLA are not supported in C++.
Suggested Solution
Use
std::vector<std::vector<int>>
to capture the 2D array.Change
to
Change the calling code to: