要将字符串作为参数传递给函数,则表示字符串的方式有种:
1. char数组;
2. 用引号括起来的字符串常量;
3. 被设置为字符串的地址的char指针
这三种类型都被认为是char指针,因此可以将其作为字符串处理函数的参数。
源码:
// Len_charptr.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include<iostream>
using namespace std;
int CallIntStr(const char* str)
{
cout <<"\n\t字符串是: "<< str << endl;
return strlen(str);
}
int main()
{
// 1.char数组
char m1[15] = { "this is char 1" };
int nResult1 = 0;
nResult1 = CallIntStr(m1);
printf("\tnResult1=%d\n", nResult1);
// 2.用引号括起来的字符串常量
nResult1 = CallIntStr("this is char 1");
printf("\tnResult2=%d\n", nResult1);
// 3.被设置为字符串的地址的char指针
char *m3 = m1;
nResult1 = CallIntStr(m3);
printf("\tnResult3=%d\n", nResult1);
}
执行结果: