Why does my C code get Runtime Error at [""]?


  • 0
    S
    char *longestCommonPrefix(char *strs[], int n) {
        if (n == 0) return "";
        if (n == 1) return strs[0];
        int j = 0;
        bool stop = false;
        while (strs[0][j] != '\0') {
            for (int i = 0; i < n; ++i) {
                if (strs[i][j] == '\0' || strs[i][j] != strs[0][j]) {
                    stop = true;
                    break;
                }
            }
            if (stop) break;
            ++j;
        }
        if (j == 0) return "";
        char *longest = malloc(sizeof(char)*(j+1));
        strncpy(longest, strs[0], j);
        longest[j] = '\0';
        return longest;
    }
    

    It said "Last executed input: [""]", but I tried this:

    char *strs[1];
    strs[0] = "";
    printf("%s\n", longestCommonPrefix(strs, 1));
    

    And it outputs empty string without any runtime error. What's the problem?


  • -2
    S

    I have the same RE problem with you. Do you know the reason now?


  • 0
    M

    me too. That's why?


  • 0
    L

    i have the same problem,have you solved it?


  • 0
    R

    I also have the problem.


  • 0
    I

    me too, but why?


  • 1
    T

    you can replace
    if (n == 0) return ""; (line 2)
    with
    if(n== 0 || strlen(strs[0]) == 0) return "";


Log in to reply
 

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