I am trying to find the minimum cost of the matrix chain multiplication by iterative dynamic programming. The snippet of the code I used is:
#include<cstdlib>
#include<iostream>
#include<stdio.h>
#include<limits.h>
using namespace std;
int MatrixChainIterative(int p[], int n)
{
int m[n][n];
for (int i=1; i<n; i++)
m[i][i] = 0;
for (int l=2; l<n; l++)
{
for (int i=1; i<n-l+1; i++)
{
int j = i+l-1;
m[i][j] = INT_MAX;
for (int k=i; k<=j-1; k++)
{
int tmp = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
if (tmp < m[i][j])
m[i][j] = tmp;
}
}
}
return m[1][n-1];
}
The code works for 700 matrices, and when I try to run the program for 800 matrices, it gives me an error. Then, I try to declare the m array outside the method and it works!
#include<cstdlib>
#include<iostream>
#include<stdio.h>
#include<limits.h>
using namespace std;
int m[n][n];
int MatrixChainIterative(int p[], int n)
{
for (int i=1; i<n; i++)
m[i][i] = 0;
for (int l=2; l<n; l++)
{
for (int i=1; i<n-l+1; i++)
{
int j = i+l-1;
m[i][j] = INT_MAX;
for (int k=i; k<=j-1; k++)
{
int tmp = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
if (tmp < m[i][j])
m[i][j] = tmp;
}
}
}
return m[1][n-1];
}
My question is why I cannot declare the 2 dimensional array inside the method? I am new with C++ and I would like to know the reason. Thank you.