反向函数用于char *抛出分段错误

时间:2013-07-17 03:31:20

标签: c++ string segmentation-fault

我有以下简单的功能:

void reverse(char* str) {
    if (str == NULL)
        return;
    char* end = str;
    while(*end != NULL) {
        end++;
    }
    end--;  
    while(str < end){
        char temp = *str;
        *str++ = *end;
        *end-- = temp;
    }   
}

int main(int argc, char* argv[]) {
    char* second = "SOMETHING\0";
    cout << "Before Reverse String: " << second << '\n';
    reverse(second);
    cout << "Reverse String: " << second << '\n';
}

简单,对吧?但是我在行

中遇到了分段错误
*str++ = *end 
*end-- = temp

我错过了什么?

谢谢!

2 个答案:

答案 0 :(得分:0)

更改

char* second = "SOMETHING\0";

char second[] = "SOMETHING";

注意:字符串文字不可修改,您不必在字符串文字中显式添加\0

while(*end != NULL) {

应该是

while(*end != '\0') {

NULL仅用于空指针。

答案 1 :(得分:0)

您正在修改字符串文字:

char* second = "SOMETHING\0";

这是未定义的行为,一种解决方案是将文字分配给char数组:

char second[] = "SOMETHING";

此外,字符串文字将以NULL结尾,因此无需添加\0。您还应该修改while循环以与\0而不是NULL进行比较。虽然它应该有用,因为它们都会评估为0,因为*endchar,使用\0会更好:

while(*end != '\0')
相关问题