Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 程序接收信号SIGSEGV,分段故障。C++;_C++_Segmentation Fault_Codeblocks - Fatal编程技术网

C++ 程序接收信号SIGSEGV,分段故障。C++;

C++ 程序接收信号SIGSEGV,分段故障。C++;,c++,segmentation-fault,codeblocks,C++,Segmentation Fault,Codeblocks,我在调试过程中遇到这个错误(*s=*end;line),同时尝试使用指针反转字符串。 我正在使用Windows10操作系统、代码块IDE和GDB调试器 #include <stdio.h> #include <string.h> #include <limits.h> void myreverse(char* s); int main() { char* s1 = "1234"; myreverse(s1); printf("%s"

我在调试过程中遇到这个错误(*s=*end;line),同时尝试使用指针反转字符串。 我正在使用Windows10操作系统、代码块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;
    }
}
#包括
#包括
#包括
void myreverse(字符*s);
int main()
{
char*s1=“1234”;
myreverse(s1);
printf(“%s”,s1);
返回0;
}
void myreverse(字符*s){
char-tmp;
char*end=s+strlen(s)-1;
对于(;s
您应该将
s1
更改为
char s1[]=“1234”因为您正在更改字符串

然后在
myreverse()
函数中,从不使用
tmp
变量,这会导致交换块失败

固定的:

#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);
}
<代码>包含/ /使用头文件的C++版本 #包括 void myreverse(字符*s){ char-tmp; char*end=s+std::strlen(s)-1; 对于(;s

请注意,交换块中的3行可以替换为,并且
myreverse()
可以完全替换为。

char*s1=“1234”应该是
const char*s1=“1234”
字符s1[]=“1234”如果您想更改它。^^^^^^这将破坏您的构建,而不是像现在这样调用未定义的行为。不要惊讶,这就是你在这种情况下想要的,因为它指出了真正的问题。然后,更改常量char*s1=“1234”
字符s1[]=“1234”,并给它另一个rip。它看起来也像
*end=*s应该是
*end=tmp