指针参数传递

----字符串传递1
void test(char *p1)
{
 strcpy(p1,"hell");
   //不能使用p1 = "hello",这样会造成类型不匹配
}


int main()

 char a[12];
 test((char *)a);
    cout << a << endl;
 return 0;
}

-----方法2
void test(char* &p1)
{
 strcpy(p1,"hell");
}


int main()

    char *p1 = new char[20];//也可以在这里只分配,也可以在函数体内部释放
 test(p1);
    cout << p1 << endl;
    delete [] p1;
 return 0;
}


---方法3
void test(char **p1)
{
        //重新分配内存,因为原来的内存不够大,
        //最好作测试看函数调用者有无free或者delete
        //只要将*p1 = "hello" 字符串常量给它,看是否出错即可
 *p1 = new char[12];
 strcpy(*p1,"hell");
}


int main()

    char *p1 = NULL;
 test(&p1);
 cout << p1 << endl;
 delete [] p1;    //这里应释放p1,因为它指向堆内存
 return 0;
}


---以下是错误的,因为在函数体内改变p1本身的值,不会影响实参p1本身的值
static char a[100];

void test(char *p1)
{
 strcpy(a,"hell");
 p1 = a;
}

int main()

 printf("%x/n",a);
 char *p1 = NULL;
 test(p1);
 printf("%x/n",p1);
 //cout << p1 << endl;
 return 0;
}


--方法4
static char a[100];

char *test()
{
 strcpy(a,"hell");
 return a;
}

int main()

 char *p1 = test();
 cout << p1 <<endl;
 return 0;
}

--方法5
char *test()
{
 char *p = new char[10];
 strcpy(p,"hello");
 return p;
}


int main()

    char *p1 = test();
 cout << p1 << endl;
 delete [] p1;    //这里应释放p1,因为它指向堆内存
 return 0;
}

如果函数及调用者都是一个人,那上述这些程序都没问题,但是如果函数和调用者是不同的人写的,
那么一定要写说明如何调用(包括大小,是否需要释放等),如果不说明,最好使用第一种方法(当然有长度问题)
因为使用这种方法只能使用字符串数组来传递,而且不需要释放堆内存。

调用其他人的这些类型的函数,一定要注意是否需要释放堆内存
自已写的这些类型的函数供其它调用,一定要写明如何调用。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值