深入理解形参的重要性

/*
#include "string.h"
#include <stdio.h>
#include <stdlib.h>
void getmemory(char **p) //函数的参数是局部变量,在这里给它分配内存还在,但是P释放了。
{
 *p=(char *) malloc(100);
 
 (*p)[0]='a';
 (*p)[1]='\0';
}
int main( )
{  
 char a[10]="eee";
 char *str=a;
 getmemory(&str);//传的 是指针的副本
 
 //strcpy(str,"hello world");
 printf("%s\n",str);
// free(str);
 return 0;
}
//要改变的是指针的指向,1  要传指针的指针。*/
 
#include "string.h"
#include <stdio.h>
#include <stdlib.h>
void getmemory(char *&p) //函数的参数是局部变量,在这里给它分配内存还在,但是P释放了。
{
 p=(char *) malloc(100);
 
 (p)[0]='a';
 (p)[1]='\0';
}
int main( )
{  
 char a[10]="eee";
 char *str=a;
 getmemory(str);//传的 是指针的副本
 
 //strcpy(str,"hello world");
 printf("%s\n",str);
 // free(str);
 return 0;
}
//要改变的是指针的指向,2 要传指针引用。
 
 
/*第三种方法-----引用调用参数传递 */
//  add中,形参c是引用类型变量,实质上c就是main中的sum的一个别名
//  add中修改c的值,就是修改了main中的sum的值
//  return 调用执行得是否ok

#include <stdio.h>
#define OK 1
typedef int status;
/*
status add(int a,int b,int c);
main()
{
    int a=2,b=3,sum=0;
    add(a,b,sum);
    printf("%d\n",sum);
}
status add(int a,int b,int c)
{
    c=a+b;
 
    return OK;
}
//传变量,只是传一个副本,不能改变变量的原来的值,
*/
 

/*
status add(int a,int b,int &c);
main()
{
    int a=2,b=3,sum=0;
    add(a,b,sum);
    printf("%d\n",sum);
}
status add(int a,int b,int &c)
{
    c=a+b;
 
    return OK;
}
////传变量的引用是变量本身,能改变变量的原来的值*/
 
/*
status add(int a,int b,int *c);
main()
{
    int a=2,b=3,sum=0;
    add(a,b,&sum);
    printf("%d\n",sum);
}
status add(int a,int b,int *c)
{
    *c=a+b;
 
    return OK;
}
//传变量的地址能改变变量的原来的值。==可以和引用互相替换*/
 

/*
status add(int a,int b,int *c);
main()
{
    int a=2,b=3,sum=0;
    add(a,b,&sum);
    printf("%d\n",sum);
}
status add(int a,int b,int *c)
{
    // *c=a+b;
 int d=6;
 c=&d;
 
    return OK;
}
//传变量的地址能改变变量的原来的值。==可以和引用互相替换*/
 
阅读(319) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~
评论热议
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值