Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/72.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++ 反向字符串:为什么会崩溃?_C++_C - Fatal编程技术网

C++ 反向字符串:为什么会崩溃?

C++ 反向字符串:为什么会崩溃?,c++,c,C++,C,我试图实现这个简单的字符串反转函数,但它一直崩溃。我已经做了一百次了,但我通常使用字符串而不是char*。我错过了什么 void reverse(char* str) { //First determine the size of the string int length = 0; char* temp = str; while(*temp) { temp++; length++; } int start = 0

我试图实现这个简单的字符串反转函数,但它一直崩溃。我已经做了一百次了,但我通常使用字符串而不是char*。我错过了什么

void reverse(char* str)
{
    //First determine the size of the string
    int length = 0;
    char* temp = str;
    while(*temp)
    {
      temp++;
      length++;
    }

    int start = 0;
    int end = length - 1;

    while(start < end)
    {
        char temp = str[start];
        str[start] = str[end];   // I get a EXEC_BAD_ACCESS here for start = 0
        str[end] = temp;
        start++; end--;
    }

    cout<<"Reversed: "<<string(str)<<endl;
}
void反向(char*str)
{
//首先确定字符串的大小
整数长度=0;
char*temp=str;
while(*temp)
{
temp++;
长度++;
}
int start=0;
int end=长度-1;
while(开始<结束)
{
char temp=str[start];
str[start]=str[end];//我在这里获得了start=0的EXEC\u BAD\u访问权限
str[end]=温度;
开始++;结束--;
}
库特

根据定义,常量不能修改。在上面的代码中,“Test”是一个字符串常量。

是否尝试反转常量(文字)字符串?这是未定义的行为。您可能希望使用strlen(char*)而不是长度查找循环
char str[]=“Test”;reverse(str)
@nneonneo啊,是的,是真的。谢谢!
str+sizeof(char)*length
:这是错误的。你很幸运
sizeof(char)==1
,但是如果你有一个
int*
,并且做了
ptr+sizeof(int)*长度
,您将无法得到预期的结果。指针算术计算了大小;不应明确包含乘数。
reverse("Test");