0

I am trying to solve a problem that i need to work with 2D array which size i read from a txt file. In order to create a 2D array "V" needs const int and later V needs to passed in print function which means it has to be global too in my implementation. What would be possible solutions for this?

void printAdjMatrix(int arr[][V])
{
    for (int i = 0; i < V; i++)
    {
        for (int j = 0; j < V; j++)
        {
            printf("%d ", arr[i][j]);
        }
        printf("\n");
    }
}

int main()
{
    fstream in("in.txt", ios::in);
    int vort;
    in >> vort;
    const int V = vort;
    int adjMatrix[V][V]; //error: expression must have a constant value
    printAdjMatrix(adjMatrix);
}
Kristers
  • 37
  • 1
  • 6

1 Answers1

0

Does this work for you?

void printAdjMatrix(int* square_mat, int dim)
{
    for (int i = 0; i < dim; i++)
    {
        for (int j = 0; j < dim; j++)
        {
            printf("%d ", square_mat[i*dim + j]);
        }
        printf("\n");
    }
}

int main()
{
    fstream in("in.txt", ios::in);
    int vort;
    in >> vort;
    const int V = vort;
    int* adjMatrix = new int[V*V](); //Use std::unique_ptr if possible
    printAdjMatrix(adjMatrix, V);
    delete[] adjMatrix;
}
Mestkon
  • 3,532
  • 7
  • 18