字符串分配seg fault - 为什么会发生这种情况?

时间:2011-05-02 05:36:54

标签: c segmentation-fault reverse

  

可能重复:
  Getting Segmentation Fault

/*  Reverse a string in place
 */
#import <stdio.h>

void reverse(char * str);

int main()
{
    char * string = "This is a string.";
    printf("%s\n", string);
    reverse(string);
    printf("%s\n", string);
}

void reverse(char * str)
{   
    char * start = str;
    char * end = str;
    if(0==*str)
        return;

    //Find the end
    for(;0 != *(++end););

    end--;
    do
    {
        *end   = *end ^ *start;
        *start = *end ^ *start;
        *end   = *end ^ *start;
    }while(++start < --end);
}

我不确定为什么这个段会出错。是因为我用常量字符串初始化我的char *?

1 个答案:

答案 0 :(得分:6)

您正在尝试修改字符串常量。替换:

char * string = "This is a string.";

char string[] = "This is a string.";

解决这个问题。