用一个函数交换数组内的两元素 come on!
有这样一个函数
void Swap(int *a,int *b)
{
int *temp;
temp=a;
a=b;
b=temp;
}用他来交换数组中第1个元素和第4个元素
int ary【1,2,3,4】
[解决办法]
come on hurry up be quick
sleeping
[解决办法]
函数内容应该是这样吧
- C/C++ code
int temp;temp=*a;*a=*b;*b=temp;
[解决办法]
- C/C++ code
void swap(int *a, int *b){ int t; t=*a; *a=*b; *b=t;}
[解决办法]
[解决办法]
int temp;
temp=*a;
*a=*b;
*b=temp;
[解决办法]
[解决办法]
这个函数是达不到元素交换目的的,函数交换的是指针变量a,b的内容,a,b原来指向单元内容并没有交换,而a,b为局部变量,函数调用结束后就释放了。
[解决办法]
[解决办法]
[解决办法]
- C/C++ code
#include <stdio.h>#define SWAP(a,b) do ((&(a))!=(&(b)))?((a)^=(b)^=(a)^=(b)):((a)=(a)); while (0)char *p1="1" ,*p2="2" ;char c1=1 , c2=2 ;short s1=1 , s2=2 ;int i1=1 , i2=2 ;__int64 I1=1i64, I2=2i64;float f1=1.0f, f2=2.0f;double d1=1.0 , d2=2.0 ;void main() { SWAP((int)p1,(int)p2); printf("char * %5s, %5s\n",p1,p2); SWAP(c1,c2); printf("char %5d, %5d\n",c1,c2); SWAP(s1,s2); printf("short %5d, %5d\n",s1,s2); SWAP(i1,i2); printf("int %5d, %5d\n",i1,i2); SWAP(I1,I2); printf("__int64 %5I64d,%5I64d\n",I1,I2); SWAP(*(int *)&f1,*(int *)&f2);printf("float %5g, %5g\n",f1,f2); SWAP(*(__int64 *)&d1,*(__int64 *)&d2);printf("double %5lg, %5lg\n",d1,d2); SWAP(c1,c1); printf("%d\n",c1);}//char * 2, 1//char 2, 1//short 2, 1//int 2, 1//__int64 2, 1//float 2, 1//double 2, 1//2