2013-03-12 90 views
-2

我正在尝试反转字符串。我带两个指针,一个指向字符串的开始,另一个指向字符串的末尾。然后我交换指针的值。当换行字符串时切换指针值时出现分段错误

int main() 
{ 

    char *string = "stack overflow"; 
    int len = strlen(string); 
    char *end; 
    char tmp; //temporary variable to swap values 

    //pointer pointing at the end of the string 
    end = string+len-1; 

    printf(" value of start and end %c %c", *string , *end); //correct values printed 
    while(string<end) 
     { 

       tmp = *string; 
       *string = *end; //segmentation fault 
       *end = tmp; 
       *string++; 
       *end--; 


     } 


    return 0; 

} 
+1

不能修改字符串常量,使用'字符字符串[] =“堆栈溢出”'而不是 – 2013-03-12 23:56:17

+2

您还没有交换指针值。你正在交换*这些指针指向的值*。无论如何,这已被问了数百次[为什么这个C代码导致了一个分段错误?](http://stackoverflow.com/questions/1614723/why-is-this-c-code-causing-a-segmentation -故障) – AnT 2013-03-12 23:57:12

回答

4
char *string = "stack overflow"; 

这将创建一个只读的字符串常量。修改它是未定义的行为。使用数组来代替:

char string[] = "stack overflow"; 
相关问题