我已经实现了两个数字的交换功能,这很有效。但是,我现在尝试交换两个字符串,但我收到的顺序相同。有人会知道我哪里出错了,或者我怎么办才能让名字改变位置?这是以下代码的示例:
#include "stdafx.h"
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
void swapages (int &age1, int &age2);
void swapname(char *person1, char *person2);
int _tmain(int argc, _TCHAR*argv[])
{
char person1[] = "Alex";
char person2[] = "Toby";
int age1 = 22;
int age2 = 27;
cout << endl << "Person1 is called " << person1;
cout << " and is " << age1 << " years old." << endl;
cout << "Person2 is called " << person2;
cout << " and is " << age2 << " years old." << endl;
swapname(person1,person2);
swapages(age1,age2);
cout << endl << "Swap names..." << endl;
cout << endl << "Person1 is now called " << person1;
cout << " and is " << age1 << " years old." << endl;
cout << "Person2 is now called " << person2;
cout << " and is " << age2 << " years old." << endl;
system("pause");
return 0;
}
void swapages(int &age1, int &age2)
{
int tmp = age2;
age2 = age1;
age1 = tmp;
}
void swapname(char *person1, char *person2)
{
char* temp = person2;
person2 = person1;
person1 = temp;
}
答案 0 :(得分:1)
您已将其标记为C ++,并且您已经包含<string>
标头,那么为什么不使用std:string
而不是所有这些指针和数组?
void swapname(string &person1, string &person2)
{
string temp(person2);
person2 = person1;
person1 = temp;
}
int _tmain(int argc, _TCHAR*argv[])
{
string person1 = "Alex";
string person2 = "Toby";
swapname(person1, person2);
}
答案 1 :(得分:0)
问题在于,当您需要交换字符串时,您正在尝试交换作为函数局部变量的指针。所以你需要将一个字符串复制到另一个字符串中。此外,琴弦可以有不同的长度,因此不可能完全交换。如果函数的参数是相同大小的数组(对数组的引用),则可以毫无问题地完成。例如
void swap_name( char ( &lhs )[5], char ( &rhs )[5] )
{
char tmp[5];
std::strcpy( tmp, lhs );
std::strcpy( lhs, rhs );
std::strcpy( rhs, tmp );
}
答案 2 :(得分:0)
您需要进行微小的更改才能让它按照您希望的方式工作。
void swapname(char **person1, char **person2);
.
.
char *person1 = "Alex";
char *person2 = "Toby";
.
.
swapname(&person1, &person2);
.
.
和
void swapname(char **person1, char **person2)
{
char* temp = *person2;
*person2 = *person1;
*person1 = temp;
}
答案 3 :(得分:0)
在你的代码中,person1和person2被定义为2个char数组而不是char指针变量,你不能交换它们,如果你将2个数组传递给swapname函数,它接受2个指针作为参数,它甚至不应该编译。