egmentation fault C语言

问题遇到的现象和发生背景

有问题

C语言代码

#include<stdio.h>
#include<string.h>
void swap(char *x, char *y){
    char temp = *x; 
    *x = *y; 
    *y = temp;
}


void main(){
    char *str = "apple";
    swap(str, str+4);
} 

报错截图:

)

img


 #include<stdio.h>
     #include<string.h>
     void swap(char *x, char *y){
         char temp = *x; 
         *x = *y; 
         *y = temp;
     }
      
      
     int main()
     {
         char str[] = "apple";
         swap(str, str+4);
         printf("%s", str); 
     } 
  

段错误,常量字符串是不可以修改的
改成 char str[] = "apple";就可以了

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632