3

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.

Cody
  • 484
  • 6
  • 20
Laura K
  • 31
  • 1
  • 1
    if by 700 and 800 you mean the parameter `n`, you may be overrunning your stack size. a stack overflow if you will. what is the error you get? – kmdreko Dec 05 '16 at 00:40
  • You can't do either of these in standard C++. C++ does not have C style variable length array declarations. The only reason this may be compiling is that your compiler apparently has an extension and your warning level isn't set high enough to tell you that you are doing something problematic. Also, even with a compiler extension, I don't believe that your second example will compile unless n is replaced by a constant in the definition of m. – Avi Berger Dec 05 '16 at 00:48
  • [This](http://stackoverflow.com/questions/23381876/how-memory-is-allocated-for-a-variable-declared-outside-vs-inside-main) might answer it. Also related: [Global Memory Management in C](http://stackoverflow.com/questions/1169858/global-memory-management-in-c-in-stack-or-heap) And [maximum stack size](http://stackoverflow.com/questions/1825964/c-c-maximum-stack-size-of-program) – Bijay Gurung Dec 05 '16 at 01:00

0 Answers0