-1

So this was a problem statement from CodeLeet to find the Longest Palindromic Substring.

In the codeleet interface this solution works:

class Solution {
public:
string longestPalindrome(string s) {
     int len = s.size();  
        int P[len][len];  
 memset(P, 0, len*len*sizeof(int));  
        int maxL=0, start=0, end=0;  
        for(int i =0; i< s.size(); i++){  
             for(int j =0; j<i; j++){  
                  P[j][i] = (s[j] == s[i] && (i-j<2 || P[j+1][i-1]));  
                  if(P[j][i] && maxL < (i-j+1))  
                  {  
                       maxL = i-j+1;  
                       start = j;  
                       end = i;  
                  }  
             }  
             P[i][i] =1;  
        }  
        return s.substr(start, end-start +1); 
   }
};

But when the write the same thing as a function in Visual Studio:

string User::longestPalindromeStr(string s) {
int len = s.size();
int P[len][len];
memset(P, 0, len*len * sizeof(int));
int maxL = 0, start = 0, end = 0;
for (int i = 0; i< s.size(); i++)
{
    for (int j = 0; j<i; j++)
    {
        P[j][i] = (s[j] == s[i] && (i - j<2 || P[j + 1][i - 1]));
        if (P[j][i] && maxL < (i - j + 1))
        {
            maxL = i - j + 1;
            start = j;
            end = i;
        }
    }
    P[i][i] = 1;
}
return s.substr(start, end - start + 1);
}

it says for the len variable : expression must have a constant value? Is it some problem with the VIsual studio ide. How can I solve this ?

blackmamba591
  • 151
  • 2
  • 11
  • Possible duplicate of [Variable-length arrays in C++?](http://stackoverflow.com/questions/1887097/variable-length-arrays-in-c) – Hans Passant Sep 28 '16 at 21:36

2 Answers2

2

Because variable length arrays (array declarations that use non-constexpr variables) are a C99 feature, not a C++ feature. No version of C++ offers them, and no version of Visual Studio provides that particular C99 feature.

If your code compiles on other C++ compilers, then that is because of C++ language extensions that they provide on top of the C++ standard.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
0

There's no problem with the VS compiler. In C++, you can use new int[] to create a 1-dimensional array of runtime defined length, but new int[][] is not available unless the 2nd dimension is a constant expression. The following attempt gives a compiler error that the 2nd dimension has to be a constant expression:

int len = 10;
int **P = new int[len][len]; // error: non-constant expression as array bound (on 2nd dimension)

This link gives a nice workaround Copy 2D array using memcpy?.

Community
  • 1
  • 1
John D
  • 1,627
  • 1
  • 11
  • 10