Producing uppercase letters without pointers

前端 未结 2 484
南笙
南笙 2021-01-25 01:12

I am trying to write a function, uppercase, that converts all lowercase characters in a string into their uppercase equivalents.

However, I am getting a Bus 10 error in

相关标签:
2条回答
  • 2021-01-25 01:30

    Your absolutly working with pointers without even to know it.

    In your function definition

    int uppercase(char source[])
    

    char source[] is considered by the compiler as a pointer to char (char *source)

    So when passing a string literal to uppercase() your just passing it's adress. Then in your function your trying to modify it which leads to undefined behaviour.

    Also you can't return a whole array so you just return a pointer to it.

    char *uppercase(char source[])
    {
         int i;
         size_t len = strlen(source);
         char *tmp;
         tmp = malloc(len+1);
         if (tmp!=NULL){
             memcpy(tmp, source, len+1);
             for(i=0; i<len; ++i){
                if (tmp[i]>= 'a' && tmp[i]<= 'z'){
                    tmp[i]= tmp[i]-'a' +'A';
                }
            }
        }
        return tmp;
    }
    

    Then:

    int main(){
        char *str = uppercase("cold");
        printf("%s", str);
        free(str);
    
        return 0;
    }
    

    You complete code: http://ideone.com/BJHDIF

    0 讨论(0)
  • 2021-01-25 01:32

    The reason you get a crash is that your code modifies a string literal. Characters inside string literals are placed in protected memory area, and therefore may not be changed: it us undefined behavior.

    Replace this

    uppercase("cold");
    

    with this:

    char cold[] = "cold";
    uppercase(cold);
    

    Now the characters of the string are placed in a modifiable area of memory, allowing you to make changes as needed.

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