How can this code not work?


  • 0
    P
    char* reverseString(char* s) {
        int length = strlen(s);
        char *rs = (char *)malloc(length);
        for (int i =0; i < length; i++) {
            *(rs + i) = *(s + length - i - 1);
        }
        *(rs + length) = '\0';
        return rs;
    }
    

    this cannot pass the test,why?


  • 0
    P

    Last executed input:
    "Trap a rat! Stare
    piper
    at Star apart."


  • 0
    Z

    You need to allocate memory of size length+1, instead of length.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.