-1

I wrote this function isPalindromic for my compsci class where the professor wants us to better understand how library functions work. So he asked us to write a function isPalindromic and mine isn't working as well. Because there are so many parts, I will paste the whole function, so bear with me. Sorry!

The function always returns false for some reason. The word passed is "HELLO ". My first loop checks for the size of the word without spaces or null characters so I can use it as a parameter in my second loop. This returns false, which is correct, but when I pass "HELLEH " or "HELLEH", they both return false. I've rewritten this at least 5 times, and I can't figure out why it's returning false.

char* isPalindromic(char inputCheck[]){
    int actWord;
    int sizeCheck = myStrLen(inputCheck);
    char tempWord[actWord];
    for(int check = 0; check <  sizeCheck; check++){
        if(inputCheck[check] = ' ' || inputCheck[check] == '\0')
            actWord = check;
    }

    for(int replace = 0; replace < actWord; replace++){
        tempWord[replace] = inputCheck[actWord - replace];
    } 

    tempWord == inputCheck ? inputCheck = "True" : inputCheck = "False";
    return inputCheck;
}
16
  • 5
    What happened to using std::string?
    – WhiZTiM
    Feb 15, 2018 at 23:12
  • 1
    actWord is not initialized
    – Mitch
    Feb 15, 2018 at 23:13
  • tempWord is a single character that you are comparing against a string
    – Mitch
    Feb 15, 2018 at 23:14
  • 3
    A warning: The question states, " to better understand how library functions work." but the given code uses no library functions. Feb 15, 2018 at 23:19
  • 1
    Aside: english.stackexchange.com/questions/1269/…
    – aschepler
    Feb 15, 2018 at 23:36

1 Answer 1

4
char tempWord[actWord];

actWord at this point is uninitialised. Your entire program therefore has undefined behaviour.


tempWord == inputCheck ? inputCheck = "True" : inputCheck = "False"; 

This is also a problem; you cannot compare two character arrays with == like this; you're just comparing their locations in memory. You'll have to use reimplement strcmp for that (although, actually, a much simpler version of your algorithm will not require such logic).


You don't need any of this extra buffer space. All you need to do is iterate from front and back simultaneously, comparing characters.

const char* isPalindromic(const char inputCheck[])
{
    const int size = myStrLen(inputCheck);
    for (size_t i1 = 0, i2 = size-1; i1 < i2; i1++, i2--)
       if (inputCheck[i1] != inputCheck[i2])
          return "False";
    return "True";
}

(live demo)

Also I would strongly consider returning a bool, not "True" or "False".

1
  • 1
    IMO, "1" or "Zero" would be better - 1 is palindromic, "Zero" isn't ;) (Seen your flag, we'll keep an eye out.)
    – BoltClock
    Feb 16, 2018 at 4:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.