strlen以及字符串动态开辟空间注意的事项

strlen以及字符串动态开辟空间注意的事项

Returns the length of the C string str.

The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).

字符串包含一串字符,并一'\0'结束,strlen会返回字符串的长度,但返回的值不会包括'\0'.
1393690-20180608210324614-1442490777.png

但我们在写代码的时候,会遇到这样的情况

class str
{
    char *p;
public:
    str(char *s)
    {
        p = new char[strlen(s)+1];
        strcpy(p,s);
    }
};
 

也就是我们要初始化一个字符串,这种情况下我们需要动态开辟空间,这个时候要开辟多大的空间值得我们思考。
刚才注意到strlen不会包含最后的NULL '\0'不会被包含,但我们要开辟的空间必须要多余strlen算出来的值,因为我们要复制给的字符串也包含'\0',因此我们开辟的空间必须是(strlen(传进来的字符串)+1).

转载于:https://www.cnblogs.com/Abudlla/p/9157571.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值