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

前情提要

字符串 做参数 传输的是地址 做返回值 返回的也是地址,但可以使用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释放空间