[Using C] why the output is wrong?


  • 0
    D
    char *convertToTitle(int n) {
        int char_size = 1;
        int num = n;
        
        //get the array size
        while (num > 0) {
            num /= 26;
            char_size++;
        }
        
        char title[char_size];
        int i = char_size - 1;
        
        title[i] = '\0';
        i--;
        
        while (i >= 0) {
            n = (n - 1) % 26;
            title[i] = 'A' + n;
            i--;
        }
        
        return title;
    }
    

    If the input is 1, the output is '''. Not as expected, someone can tell me why?


  • 1

    Because title is a local variable and you are returning it from the function. Once the function returns, accessing the pointer that points to title's location is undefined behavior, as there is no guarantee that the address space of title will not be used/overridden. You basically have two options:

    1. Define title as a static character array with predefined size, such as static char title[256].
    2. Allocate space for title using malloc and return it.

Log in to reply
 

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