-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;

}
4

1 回答 1

5
char *string = "stack overflow";

这将创建一个只读字符串文字。修改它是未定义的行为。改用数组:

char string[] = "stack overflow";
于 2013-03-12T23:56:15.757 回答