-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 ?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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?.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.