地址传递用法

来源:互联网 发布:java自学书籍推荐书目 编辑:程序博客网 时间:2024/06/06 20:55
#include <iostream>
using namespace std;
//传值调用
void GetMemory( char **p )
{
*p = (char *) malloc( 100 );
}
//引用调用
void GetMemory_1(char *&p)
{
p = (char *) malloc (100);
}

int main()
{
char *str = NULL;
char *str1 = NULL;
GetMemory( &str );
GetMemory_1( str1 );
strcpy( str, "hello world" );
strcpy( str1, "hello world1" );
cout<<str<<endl;
cout<<str1<<endl;
free(str);
free(str1);
return 0;
1
}

void GetMemory( char *p )
函数在内部改变形参值,不改变原传入变量的值
void GetMemory( char *&p )
使用参数引用,可改变原变量的值
函数结束要对str进行free

0 0