2010-07-03 66 views
6
#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"; 
+0

也许是一个不同的标题?虽然这个例子是反转字符串的代码,但实际的问题是关于修改数组和字符串文字 – akf 2010-07-03 16:54:09

+0

你有没有理由不使用'strrev()'?此外,这将打破多字节字符。 – Piskvor 2010-07-03 17:19:51

回答

13

您的代码试图修改文本字符串这是不是在C允许或C++如果你改变:

char *s = "hello"; 

到:

char s[] = "hello"; 

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

4

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

0

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

0

你可以试试这个:

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

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

注意,它不处理字符串结束。