字符串做函数参数和返回值

前情提要

字符串 做参数 传输的是地址 做返回值 返回的也是地址,但可以使用const来禁止对字符串参数进行修改。

字符串做参数

假设要将字符串作为参数传递给函数,则表示字符串的方式有三种:

  • char数组
  • 用引号括起的字符串常量(也称字符串字面值);
  • 被设置为字符串的地址的char指针。
类型样式
字符串常量“iloveyou”
被设置为字符串地址的char指针char* str=“iloveyou”
char数组char arry[]=“iloveyou”

将字符串作为参数来传递,实际传递的是字符串第一个字符的地址。这意味着字符串函数原型应将其表示字符串的形参声明为char *类型。

假设有函数 void strken(char*)
则应用时可以写成

strken("iloveyou");//字符串首字符地址
strken(arry);//arry[0]的地址
strken(str);//指向字符串首地址的指针

字符串作为返回值

首先要明确,函数无法返回一个字符串,但可以返回字符串的地址。
看代码

#include <iostream>
char* buildstr(char,int );
int main()
{
using namespace std;
int times ;
char ch ;
cout <<  " Enter a character : " ;
cin >> ch ;
cout << " Enter an integer : " ;
cin >> times ;
char *ps =buildstr ( ch , times );
printf("%p\n",ps);//用来输出地址
cout << ps << endl ;
delete [] ps;
// free memory
ps = buildstr ( '+' , 20 ) ;
// reuse pointer
cout << ps << " - DONE-" << ps << endl ;
printf("%p\n",ps);
delete [] ps;
// free memory
return 0;
}
// builds string made of n c characters
char * buildstr ( char c , int n )
{
char * pstr = new char [ n + 1 ] ;
printf("%p\n",pstr);//用来输出地址;
pstr[n] = '\0 ' ;
// terminate string
while ( n-- > 0 )
pstr[n]=c;
// fill rest of string
return pstr ;
}

这是运行结果
在这里插入图片描述
首先,可以看到函数返回的是地址,其次,ps指向的地址实际就是函数buildstr里面用new运算符创造的空间,所以在主函数中,用了delete释放空间

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值