This question already has answers here:
Why do I get a segmentation fault when writing to a string initialized with “char *s” but not “char s[]”?
                                
                                    (17个答案)
                                
                        
                                2年前关闭。
            
                    
#include<stdio.h>
#include<string.h>
int main(){
    char *a[]={"this","is","a","string"};
    char temp[100];
    for(int i=0;i<3;i++){
        for(int j=0;j<3-i;j++){
            if(strcmp(a[j],a[j+1])>0){
                strcpy(temp,a[j]);
                strcpy(a[j],a[j+1]);
                strcpy(a[j+1],temp);
            }
        }
    }
    for(int i=0;i<4;i++){
        printf("%s\n",a[i]);
    }
}


以下代码用于对字符串进行冒泡排序,这会导致分段错误,这有什么问题?

最佳答案

字符串文字在C中是只读的。您的strcpy(a[j],a[j+1])strcpy(a[j+1], temp)调用是非法的。

09-05 06:51