分段错误反转字符串文字

时间:2010-07-03 16:25:25

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

4 个答案:

答案 0 :(得分:14)

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

char *s = "hello"; 

为:

char s[] = "hello"; 

然后你正在修改数组的内容,文本已被复制到该数组中(相当于用单个字符初始化数组),这没关系。

答案 1 :(得分:4)

如果执行char s[6] = {'h','e','l','l','o','\0'};,则将6 char放入堆栈中的数组中。当你执行char *s = "hello";时,堆栈上只有一个指针,它指向的内存可能是只读的。写入该内存会导致未定义的行为。

答案 2 :(得分:0)

对于某些版本的gcc,您可以允许使用-fwritable-strings修改静态字符串。并不是说有这么好的借口。

答案 3 :(得分:0)

你可以试试这个:

void strrev(char *in, char *out, int len){
    int i;

    for(i = 0; i < len; i++){
        out[len - i - 1] = in[i];
    }
}

请注意,它不处理字符串终止符。

相关问题