简体   繁体   中英

Is it applicable to pass pointer to character (after assigning string to it) to method and modify this string after without using array and why not?

I want to pass string to ac function using pointer to char and modify it and it gave me segmentation fault. I don't know why ? Note*: I know I can pass the string to array of character will solve the problem

I tried to pass it to array of character and pass to function the name of array and it works , but I need to know what the problem of passing the pointer to character.

void convertToLowerCase(char* str){

    int i=0;
    while(str[i] != '\0')
    {
        if(str[i]>='A'&& str[i]<='Z'){
            str[i]+=32;
        }
        i++;
    }
}

int main(void){

    char *str = "AHMEDROSHDY";
    convertToLowerCase(str);
}

I expect the output str to be "ahmedroshdy", but the actual output segmentation fault

This (you had char str* which is a syntax error, fixed that):

char *str = "AHMEDROSHDY";

is a pointer to a string literal , thus it cannot be modified, since it is stored in read-only memory.

You modify it here str[i]+=32; , which is not allowed.

Use an array instead, as @xing suggested, ie char str[] = "AHMEDROSHDY"; .

To be more precise:

char *str = "AHMEDROSHDY";

'str` is a pointer to the string literal. String literals in C are not modifacable

in the C standard:

The behavior is undefined in the following circumstances: ...

  • The program attempts to modify a string literal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM