程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 指針實現交換兩個數字的大小

指針實現交換兩個數字的大小

編輯:關於C語言

#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;
    }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved