2010-07-03 63 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]; 
    } 
} 

注意,它不處理字符串結束。