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'.

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

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

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

猜你喜欢

转载自www.cnblogs.com/Abudlla/p/9157571.html