[英]Program received signal SIGSEGV, Segmentation fault. C++
I'm getting this error (*s = *end; line) during debugging, while trying to reverse string using pointers.我在调试期间遇到此错误(*s = *end; line),同时尝试使用指针反转字符串。 I'm using Windows 10 OS, codeblocks IDE and GDB debugger.我正在使用 Windows 10 操作系统,代码块 IDE 和 GDB 调试器。
#include <stdio.h>
#include <string.h>
#include <limits.h>
void myreverse(char* s);
int main()
{
char* s1 = "1234";
myreverse(s1);
printf("%s", s1);
return 0;
}
void myreverse(char* s) {
char tmp;
char* end = s + strlen(s) - 1;
for(; s < end; s++, end--) {
tmp = *s;
*s = *end;
*end = tmp;
}
}
You should change s1
to char s1[] = "1234";
您应该将s1
更改为char s1[] = "1234";
since you are making changes to the string.因为您正在更改字符串。
Then in your myreverse()
function, you never use the tmp
variable, which makes your swap block failing.然后在您的myreverse()
function 中,您永远不会使用tmp
变量,这会使您的交换块失败。
Fixed:固定的:
#include <cstdio> // use the C++ versions of the header files
#include <cstring>
void myreverse(char* s) {
char tmp;
char* end = s + std::strlen(s) - 1;
for(; s < end; s++, end--) {
// swap
tmp = *s;
*s = *end;
*end = tmp; // use tmp
}
}
int main() {
char s1[] = "1234";
myreverse(s1);
printf("%s", s1);
}
Note that the 3 lines in the swap block can be replaced with std::swap(*s, *end);
请注意,交换块中的 3 行可以替换为std::swap(*s, *end);
and also that myreverse()
can be completely replaced with std::reverse(std::begin(s1), std::end(s1));
而且myreverse()
可以完全替换为std::reverse(std::begin(s1), std::end(s1));
. .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.