Capitalize string and return local variable

后端 未结 3 542
予麋鹿
予麋鹿 2020-12-22 05:16

I\'m trying to make a procedure that will capitalize a string, but I get junk values and a warning from gcc that I\'m returning the address of a local variable. Coming from

相关标签:
3条回答
  • 2020-12-22 06:04

    First of all, you should always put a null character at the end of a string, because the standard library uses this to denote the actual end of a string, to prevent from walking over memory.

    This is an implementation.

    /* Makes a copy of the string as to not modify the original buffer */
    char* makeCopy(char* s){
    
        char* buff = (char*) malloc(len(s) + 1);
        strcpy(buff, s);
        return buff;
    }
    
    /* Converts the string to uppercase */
    char* toUpperCase(char* s){
    
            char* q = makeCopy(s);
            int i;
            for(i = 0; i < len(q); i++){
                    *(q + i) = toupper(*(q + i));
            }
    
            return q;
    
    }
    

    Now you can do:

    printf("I expect capitalized version of edgar, I got %s\n", toUpperCase("edgar"));
    

    Now I understand that you don't want to touch any of the stuff in string.h, but it is useful, for without the functions there you may need to implement much of the stuff on your own.

    For example, the function toupper() comes from string.h. This converts a character to its uppercase equivalent. If you insist on reinventing the wheel you can hack a tiny function that handles it.

    char getUpperCaseChar(char lower){
        if(lower < 91)
            return lower;
        if(lower > 96)
            return (lower - 32);
    }
    
    0 讨论(0)
  • 2020-12-22 06:06

    is this a case when I should use malloc?

    Yes, exactly.

    In your case, you return pointer to local variable, which (the variable) will be destroyed after the execution of the function. This makes the pointer dangling.

    Using malloc will create the string in the heap, not stack, and it will remain valid after after the return of the function.

    0 讨论(0)
  • 2020-12-22 06:15

    You have two options in C.

    1) you can pass your function an pointer to the string and function will modify it and return void

    In this case you can just use the original string

    2) you can pass your function const char* and return char *, but then you need to malloc inside the function

    If you do a malloc inside function, you can then use the string (print it or do whatever you want), at the and of the program you call free

    0 讨论(0)
提交回复
热议问题