下面程序段的功能是交换两个字符数组的内容(每个字符串字符数均不超过100).(8分)
void StrSwap(char *pa,char *pb)
{
char *temp;
temp = pa;
pa = pb;
pb = temp;
}
完整代码:
# include <iostream>
using namespace std;
void StrSwap(char *pa, char *pb)
{
char *temp;
temp = pa;
pa = pb;
pb = temp;
for (int i = 0; i < 3; i++) {
cout << pa[i]<<" ";
}
cout << endl;
for (int i = 0; i < 3; i++) {
cout << pb[i] << " ";
}
}
int main(void) {
char a[3] = {'1','2','3'};
char b[3] = { '6','8','9' };
StrSwap(a,b);
system("pause");
return 0;
}
结果:
C语言中实参形参变量之间的数据传递是单向的“值传递”,用指针变量作函数参数是同样要遵循这一规则。
不可能通过执行调用函数来改变实参指针变量的值,但是可以改变实参变量所指变量的值。
{
char temp
temp= *pa;
*pa= *pb;
*pb= temp;
}
完整代码:
# include <iostream>
using namespace std;
void StrSwap2(char *pa, char *pb)
{
char temp;
temp = *pa;
*pa = *pb;
*pb = temp;
for (int i = 0; i < 3; i++) {
cout << pa[i] << " ";
}
cout << endl;
for (int i = 0; i < 3; i++) {
cout << pb[i] << " ";
}
}
int main(void) {
char a[3] = {'1','2','3'};
char b[3] = { '6','8','9' };
StrSwap2(a,b);
system("pause");
return 0;
}
结果: