C:字符交换

g3d*_*g3d 4 c pointers char

我需要通过指针交换两个字符,但是运行此代码时,程序崩溃。

int main(){
    char *s1 = "string1";
    swap(st,(st+1));

    /* BUT THIS CODE WORKS - Whats the problem?
     * char s1[] = "string1";
     * swap(s1,&s1[1]);
     */

    return 0;
}

void swap(char * const ptr1, char * const ptr2){

    char temp = *ptr1;
    *ptr1 = *ptr2;
    *ptr2 = temp;

}
Run Code Online (Sandbox Code Playgroud)

P.P*_*.P. 5

char *s1 = "string1";
Run Code Online (Sandbox Code Playgroud)

因为s1指向字符串文字并进行修改会调用C中的未定义行为。这就是为什么此方法不起作用的原因。

而在此 char s1[] = "string1";

s1 是一个数组,因此可以修改。