This is Leetcode's palindrome problem, which I solved with JavaScript. Then I decided to try it with C and the problem I'm running into is that if I define the array by value, when I would try to return a pointer to it, it would show up as NULL. After some research on here, I found that declaring an array would put it on the stack instead of the heap and that space in memory is reclaimed when the function closes, so I was returning an undefined spot in memory.
The problem I have is that I can't seem to create a character array using malloc. I don't know if it's the syntax I'm getting wrong or something I'm missing. It's been a while since I used C, so I'd appreciate any help.
char * longestPalindrome(char * s) {
int strLength=strlen(s);
/* char longestPal[strLength]; */
/* works as far as the logic is concerned but can't return a pointer to it */
/* the trouble spot I need help with */
char *longestPal = malloc(sizeof(*char) * strLength);
/* compiler error */
for (int i = 0; i <strLength; i++) {
/* first check for longest even palindrome */
findPalindrome(i, i, strLength, longestPal, s);
/* Next check for longest odd palindrome */
findPalindrome(i, i + 1, strLength, longestPal, s);
}
return longestPal;
}
void findPalindrome (int left, int right, int strLength, char *longestPal, char *s) {
int i, j;
while (left >= 0 && right < strLength && s[left--] == s[right++])
if ((right - left) > strlen(longestPal)) {
j = 0;
for (i = left + 1; i < right; i++) {
longestPal[j] = s[i];
j++;
}
}
return;
}
Edit After giving up on allocating memory, I went in a slightly different direction and decided to work within the already allocated memory in the parameter *s. I admit I was looking for inspiration from another solution and changed my "middle-out" palindrome finder function to just give me the length of the palindromes and I would use that to determine the longest and then use that to return the address to the correct part of the palindrome.
char * longestPalindrome(char * s){
int strLength=strlen(s); /*doing this so I don't keep calling strlen and waste resources*/
int start=0, end=0;
int tempMax1, tempMax2, max;
int i=0;
if (s==NULL || strLength<1)
return "";
for(i=0; i<strLength; i++)
{
/*first check for longest even palindrome*/
tempMax1 = findPalindrome(i,i, strLength, s);
/*Next check for longest odd palindrome*/
tempMax2= findPalindrome(i, i+1,strLength, s);
/*keep track of the longest palindrome found*/
max= tempMax1 > tempMax2? tempMax1:tempMax2;
if (max > end-start)
{
start = i-(max-1)/2;
end= i+max/2;
}
}
/*we need a way to indicate the end of the palindrome
* easiest way is to mark the end with the NULL character
*/
s[end+1]='\0';
return &s[start];
}
/*will return the length of the palindromes it finds
* and then the maximum will be determined by the main function
*/
int findPalindrome (int left, int right, int strLength, char *s)
{
while (left>=0 && right < strLength && s[left]==s[right])
{
left--;
right++;
}
return (right-left-1);
}