当前位置:天才代写 > tutorial > C语言/C++ 教程 > 指针实现互换两个数字的巨细

指针实现互换两个数字的巨细

2017-11-02 08:00 星期四 所属: C语言/C++ 教程 浏览:451

#include <stdlib.h>
#include <stdio.h>
void swap(int *x,int *y)
{
    int tmp;
    tmp = *x;
    *x = *y;
    *y = tmp;

}
int main(void)
{   
    int *x,*y;
    x = (int *)malloc(sizeof(int));
    y = (int *)malloc(sizeof(int));
    /*check if malloc is successful*/
    if(x == NULL || y == NULL)
    {
        return -1;
    }
    else
    {
        printf("The address x pointed to is %d\n",x);
        printf("The address y pointed to is %d\n",y);
        *x = 1;
        *y = 2;
        swap(x,y);/*call function*/
        printf("The address x pointed to is %d\n",x);
        printf("The address y pointed to is %d\n",y);
        printf("x is %d \n",*x);
        printf("y is %d \n",*y);
        free(x);
        free(y);
        x = NULL;
        y = NULL;
        int a = 100;
        int b = 200;
        swap(&a,&b);/*call function*/
        printf("a is now %d.\n",a);
        printf("b is now %d.\n",b);
        return 0;
    }
}

 

    关键字:

天才代写-代写联系方式