我有以下简单的功能:
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
我错过了什么?
谢谢!
最佳答案
你正在修改一个字符串文字:
char* second = "SOMETHING\0";
这是未定义的行为,一种解决方案是将文字分配给 char 数组:
char second[] = "SOMETHING";
此外,字符串文字将以 NULL 结尾,因此不需要添加 \0
。您还应该修改 while 循环以与 \0
而不是 NULL
进行比较。虽然,它应该工作,因为它们都将评估为 0
因为 *end
是一个 char
它更好地阅读使用 \0
:
while(*end != '\0')
关于c++ - char * 抛出段错误的反向函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17690610/