第二次作业

#include<stdio.h>
#include<stdlib.h>
void swap(int* x, int* y)  //输入一个swap函数
{
    int t = *x;    //定义一个变量
    *x = *y;
    *y = t;      //运用指针交换值
    return;
}
int main()
{
    int a = 3, b = 4;//给两个整形赋值
    swap(&a,&b);  
    printf("%d %d\n", a, b);
    return (0);
}

 

4 3

--------------------------------
Process exited after 0.5544 seconds with return value 0
请按任意键继续. . .

 

 2、void swap(int *p,int *q){int *m;*m=*p;*p=*q;*q=*m;}为何无法实现交换?

这个报错的是程序错误

首先,int的*m是一个指针,是一个地址,地址是随机给的,所以有可能和需要交换地址的两个指针地址重复。所以无法实现交换

(自己理解)

 

 3、void swap(int *p,int *q){int *m;m=p;p=q;q=m;}为何无法实现交换?

这个程序没有错误,但是运行后两个整形并没有交换数据

因为前面所输入的都是指针,但交换的时候却是以整形的格式交换的,所以两个指针的地址并没有交换。所以无法实现交换。

 

 

#include<stdio.h>
int comp(int *a,int *b)
{
    if(*a>*b)
        return *a;
    else
        return *b; 
}
int main(void)
{
    int a,b,*i,*j;
    scanf("%d %d",&a,&b);
    i = &a;
    j = &b;
    printf("MAX=%d\n",comp(i,j));
}
3 25
25

--------------------------------
Process exited after 91.82 seconds with return value 3
请按任意键继续. . .

 

总结:指针的应用很广泛,而且指针是运用地址来数据转换,方便而且快速,不易弄混数据。

posted @ 2017-03-22 13:02  王丫  阅读(226)  评论(0编辑  收藏  举报