读书人

用一个函数互换数组内的两元素 come on

发布时间: 2012-09-13 09:51:52 作者: rapoo

用一个函数交换数组内的两元素 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;}
[解决办法]
探讨
函数内容应该是这样吧

C/C++ code

int temp;
temp=*a;
*a=*b;
*b=temp;



调用方法:

C/C++ code

int a[4] = { 1, 2, 3, 4 };
Swap( a + 0, a + 3 );

[解决办法]
int temp;
temp=*a;
*a=*b;
*b=temp;




[解决办法]
探讨

我想不懂为什么我那个哪里错了
这不是temp指向a的地址了吗
a指向b的地址
b再指向a的地址吗
temp=a;
a=b;
b=temp;

[解决办法]
这个函数是达不到元素交换目的的,函数交换的是指针变量a,b的内容,a,b原来指向单元内容并没有交换,而a,b为局部变量,函数调用结束后就释放了。
[解决办法]
探讨
引用:

我想不懂为什么我那个哪里错了
这不是temp指向a的地址了吗
a指向b的地址
b再指向a的地址吗
temp=a;
a=b;
b=temp;

因为,在函数里,a,b虽然是指针,但是它本身只是个临时变量,修改a,b指向的内容,和你的数组没任何关系

a,b只是你传进来参数的两个副本

int arr[4] = {1, 2, 3, 4};
调用S……

[解决办法]
探讨

我想不懂为什么我那个哪里错了
这不是temp指向a的地址了吗
a指向b的地址
b再指向a的地址吗
temp=a;
a=b;
b=temp;

[解决办法]
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 

读书人网 >C语言

热点推荐