C : Character swapping

标签 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;

}

最佳答案

char *s1 = "string1";

因为 s1 指向一个字符串文字并且修改调用 undefined behaviour在 C 中。这就是为什么这不起作用。

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

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

关于C : Character swapping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14546969/

相关文章:

c# - 为什么我不经常看到更严格的范围界定?

c - 在C中访问Excel工作表单元格属性

c - 从编辑框获取文本

c - C 中指针语法的初学者

c - 如何在C中对单个字符执行scanf

CryptDecrypt 失败并显示 NT_BAD_DATA (0x80090005)

c - 理解指针数组

c++ - 为什么跨两个 block 的共享内存的指针位置相同?

CodeBlocks exe 停止工作

C++ 连接字符串导致 "invalid operands of types ‘const char*’ 和 ‘const char"