C ++交换字符串 [英] C++ Swap string

查看:135
本文介绍了C ++交换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个非递归方法来交换c风格的字符串。它在Swap方法中抛出异常。无法找出问题。

I am trying to create a non-recursive method to swap a c-style string. It throws an exception in the Swap method. Could not figure out the problem.

void Swap(char *a, char* b)
{
    char temp;
    temp = *a;
    *a = *b;
    *b = temp;
}
void Reverse_String(char * str, int length)
{
    for(int i=0 ; i <= length/2; i++)  //do till the middle
    {
        Swap(str+i, str+length - i);

    }

}

知道有鸽友的方法来做到这一点。但因为我在学习,想知道代码的问题。

I know there are fancier ways to do this. But since I'm learning, would like to know the problem with the code.

推荐答案


在Swap方法中抛出异常。无法找出问题。

It throws an exception in the Swap method. Could not figure out the problem.

不是。创建临时字符和分配字符不能抛出异常。

No it doesn't. Creating a temporary character and assigning characters can not possibly throw an exception. You might have an access violation, though, if your pointers don't point to blocks of memory you own.

Reverse_String()

The Reverse_String() function looks OK, assuming str points to at least length bytes of writable memory. There's not enough context in your question to extrapolate past that. I suspect you are passing invalid parameters. You'll need to show how you call Reverse_String() for us to determine if the call is valid or not.

如果你正在这样写:

char * str = "Foo";
Reverse_String(str, 3);
printf("Reversed: '%s'.\n", str);

那么你肯定会得到访问冲突,因为 str 指向只读存储器。请尝试使用以下语法:

Then you will definitely get an access violation, because str points to read-only memory. Try the following syntax instead:

char str[] = "Foo";
Reverse_String(str, 3);
printf("Reversed: '%s'.\n", str);

这实际上会复制Foo string into a local buffer you can overwrite。

This will actually make a copy of the "Foo" string into a local buffer you can overwrite.

这篇关于C ++交换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆