c - 反转字符串文字的段错误

标签 c

<分区>

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    //char s[6] = {'h','e','l','l','o','\0'};
    char *s = "hello";       
    int i=0,m;
    char temp;

    int n = strlen(s);
    //s[n] = '\0';
    while (i<(n/2))
    {
         temp = *(s+i);       //uses the null character as the temporary storage.
         *(s+i) = *(s+n-i-1);
         *(s+n-i-1) = temp;
         i++;
    }
    printf("rev string = %s\n",s);
    system("PAUSE");
    return 0;
}

编译错误是段错误(访问冲突)。请说出这两个定义有什么区别:

char s[6] = {'h','e','l','l','o','\0'};
char *s = "hello"; 

最佳答案

您的代码试图修改 C 或 C++ 中不允许的字符串文字如果您更改:

char *s = "hello"; 

到:

char s[] = "hello"; 

然后你正在修改数组的内容,文字已被复制到其中(相当于用单个字符初始化数组),这是可以的。

关于c - 反转字符串文字的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3172075/

相关文章:

c - 声明没有最高维度的数组

c - 如何让 printf 语句只有这么长?

c - 使用 libavformat 和 libswscale 提取视频帧图像给出翻转图像

将包含多个单词的字符串转换为字符数组

c - 将 32 位值分配给 64 位变量并保证前 32 位在 C 中为 0 的最佳方法

c - 如何创建具有未定义类型的独立链接列表标题

c - 如何从二进制文件读取到 C 中的文本文件?

c - 无法处理号码 600851475143,但我可以完美处理 13195

c - 何时在 C 中将 '*' 放在指针之前

c - 基于CLRS教科书的归并排序