指针作为函数参数,函数没有返回值,主函数如何调用
/* 输入两个整数a和b,按先大后小的顺序输出(利用函数实现)*/#include <stdio.h>
void main ()
{
int a,b;
int *pointer1,*pointer2;
void swap(int *pointer1,int *pointer2);
printf("Please input two int numbers :\n");
scanf("%d,%d",&a,&b);
pointer1 = &a;
pointer2 = &b;
if(a<b)
{
swap(pointer1,pointer2);
}
printf("a = %d, b = %d\n",a,b);
printf("%d > %d\n",*pointer1,*pointer2);
}
void swap(int *pointer1,int *pointer2)
{
int *p;
p = pointer1;
pointer1 = pointer2;
pointer2 = p;
} ba21 发表于 2017-7-21 14:51
运行完之后结果是错误的,加入输入3,4,结果会输出3>4 本帖最后由 ba21 于 2017-7-21 16:15 编辑
fyt110 发表于 2017-7-21 15:43
运行完之后结果是错误的,加入输入3,4,结果会输出3>4
你这个swap里面的pointer1,pointer2 是形参,是局部指针,只能修改它指向的值,
帮你改下代码如下,看你好不好理解:
#include <stdio.h>
void main ()
{
int a,b;
int *pointer1,*pointer2;
void swap(int *x,int *y);
printf("Please input two int numbers :\n");
scanf("%d,%d",&a,&b);
pointer1 = &a;
pointer2 = &b;
if(a<b)
{
swap(pointer1,pointer2);
}
printf("a = %d, b = %d\n",a,b);
printf("%d > %d\n",*pointer1,*pointer2);
}
void swap(int *x,int *y)
{
int *p;
p = x;
x = y;
y = p;
}
修改指向值的代码 如下:
#include <stdio.h>
void main ()
{
int a,b;
int *pointer1,*pointer2;
void swap(int *x,int *y);
printf("Please input two int numbers :\n");
scanf("%d,%d",&a,&b);
pointer1 = &a;
pointer2 = &b;
if(a<b)
{
swap(pointer1,pointer2);
}
printf("a = %d, b = %d\n",a,b);
printf("%d > %d\n",*pointer1,*pointer2); //或 printf("%d > %d\n",a,b);
}
void swap(int *x,int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
页:
[1]