这个反向数组代码在c ++中有什么问题?

时间:2015-03-17 03:20:41

标签: c++ arrays pointers char

程序编译正常,但在运行时崩溃并显示: 流程终止,状态为-1073741819

void reverse(char *str){

    char * end1 = str;
    char tmp = 'c';
    if(str){
        while(*end1){
            ++end1;
        }
        --end1;

        while(str<end1){
            tmp=*str;
            *str=*end1;
            *end1=tmp;
            str++;
            end1--;
        }
    }
}

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您的reverse实现完全没有问题:只要您传递的字符串为空终止且可写,您的代码就会正常工作。

然后调用它的方式肯定有问题。最常见的可能性是传递字符串文字,写入可能导致崩溃的未定义行为:

char *s = "quick brown fox";
reverse(s); // <<== This would be undefined behavior

Demo of your working code