现在的位置: 首页 > 综合 > 正文

值交换和字符交换的对比

2013年11月21日 ⁄ 综合 ⁄ 共 743字 ⁄ 字号 评论关闭

void swap_int(int a, int b) 

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

void swap_int(int *a, int *b) 

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

void swap_str(char *a, char *b)  //两字符串没有交换
{  //交换了两个字符串的地址,按值传递
    char *temp = a; 
    a = b; 
    b = temp; 

 void swap_str(char **a, char **b) 

    char *temp ;
 temp=*a;
    *a = *b; 
    *b = temp; 
}
int main() 

    int a = 10; 
    int b = 5; 
    int a1=2;
    int b1=3;
    char *str_a = "hello world"; 
    char *str_b = "world hello"; 

    swap_int(a, b);  
    swap_str(str_a, str_b); 
    printf("%d, %d,%d, %d, %s, %s", a, b, a1,b1,str_a, str_b);     
//10, 5, hello world, world hello
//都是按值传递,不改变原值

  swap_int(&a1,&b1);
 printf("%d, %d ,a1,b1);  //3,2

 char *str_a1= "hello ";  
   char *str_b1= "world ";    
 swap_str(&str_a1, &str_b1);  
 printf(" %s, %s", str_a1, str_b1);//world, hello
    return 0; 

抱歉!评论已关闭.