c - 用指针反转 C 中的字符串文字

标签 c

<分区>

虽然我的代码在 *head=*tail 行接收到 SEGSIGV 信号,但我正在尝试使用指针来反转字符串文字

char* reverse(char* input, int n) {
    char temp;
    char* head= input;
    char* tail= &input[n-1];
    while(head<tail){
        temp=*head;
        *head=*tail;
        *tail=temp;
        head++;
        tail--;
    }
    return input;
}


int main(void){
    char* sentence= "All work and no play makes jack a dull boy";
    reverse(sentence, strlen(sentence));
    printf("%s", sentence);
    return 0;
}

我不知道我是否在尝试访问受限的内存段。

最佳答案

是的,您正在尝试修改只读内存。
您不能重新排列常量字符串。

通过简单的更改,您可以修复它:

char sentence[] = "All work and no play makes jack a dull boy";

(使用数组而不是指针)

关于c - 用指针反转 C 中的字符串文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43350179/

相关文章:

c - 对c中的指针和数组进行澄清

c++ - 写(函数原型(prototype)、函数指针、外部指针)更小

c - 链接器不通知多个定义

c - exec 是否保留文件描述符

c - 如何在c中输入和扫描多个字符

c - 为什么 putenv(buf) 无法正常工作,因为 memcpy(buf + 92, "\x00\x14\xe4\xf7", 4) 将 a\x00 字节复制到 buf ?

c - 如何找到最小的行和(二维数组)C 编程

时钟不准确

c# - 如何通过 out 参数将变量从 iOS native 代码返回到 C#?

C 静态分配与动态分配