分析上面的程序代码:
PS:返回指针的时候,切忌返回局部变量,因为局部变量生命周期截止到大括号
错误示例:
//使用下面这个函数会报错,因为strRt是局部变量。
char* cstr1(const char* cmem)
{
int len = clen(cmem);
char strRt[0xff];//开辟空间,接收cmem的内容
memcpy(strRt, cmem, len);
return strRt;
}
完整的正确示例:
#include <iostream>
//计算字符串长度
int clen(const char* ary)
{
int i{};
for (i = 0; ary[i]; i++);
return i+1;
}
//将字符串进行一个转换【const char*转到char*】
char* cstr(const char* cmem)
{
int len = clen(cmem);
char* strRt = new char[len];
memcpy(strRt, cmem, len);
return strRt;
}
int main()
{
char* strA{};
strA = cstr("你好");
std::cout << strA << std::endl;
}
设计函数:
结构体:
typedef struct Role
{
char* name;
int Hp;
int MaxHp;
int Mp;
int MaxMp;
unsigned lv;
}*Prole;
创建英雄:
Prole CreateRole(const char* name, int hp, int mp)
{
Prole role = new Role{ cstr(name),hp,hp,mp,mp,1 };
return role;
}
改写成引用:
Role& CreateRole(const char* name, int hp, int mp)
{
Prole role = new Role{ cstr(name),hp,hp,mp,mp,1 };
return *role;
}
int main()
{
char* strA{};
strA = cstr("你好");
std::cout << strA << std::endl;
Role& user = CreateRole("奥特曼", 1000, 1000);
std::cout << user.name << std::endl;
std::cout << user.Hp << "/" << user.MaxHp << std::endl;
std::cout << user.Hp << "/" << user.MaxHp << std::endl;
}
下面的代码例子:
如果int c[50];
那么int (&e)[100]=c;就会报错
可以通过引用将数组传入函数内
int ave(int (&mem)[5])//这个数组的元素只能固定,
{
..........
}
在c++中strcpy()函数不能用,因C ++strcpy()函数运行不安全,并且具有更安全的函数代替。而取代替strcpy()的函数是strcpy_s(),接下来介绍strcpy_s()具体用法。
首先要包含头文件<cstring>,strcpy_s()函数被包含在此头文件中,此函数不在std名字空间中,记得不要使用语句:using namespace std;。
接着来介绍该函数参数,该函数参数有两种形式,
一、三个参数:
strcpy_s(char* a(把复制的内容复制到此指针), int b(复制长度), char const* c(被复制指针));
二、两个参数:
strcpy_s(char* a(把复制的内容复制到此指针),char const* c(被复制指针)
具体介绍如下
#include <iostream>
#include <cstring>
int main()
{
char p[10];
std::cin >> p;
char p1[10];
strcpy_s(p1, p);//数组的数组名是一个常量指针
std::cout << "p1 = " << p1 ;
return 0;
}
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- hzar.cn 版权所有 赣ICP备2024042791号-5
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务