sizeof运算符和strlen()函数作用于c、c++风格字符串

说明:
1、strlen()函数:
以下来自cplusplus.com:



size_t strlen ( const char * str );

Get string length
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).

This should not be confused with the size of the array that holds the string. For example:

char mystr[100]="test string"; 

defines an array of characters with a size of 100 chars, but the C string with which mystr has been initialized has a length of only 11 characters. Therefore, while sizeof(mystr) evaluates to 100, strlen(mystr) returns 11.

In C++, char_traits::length implements the same behavior.



strlen(…)是函数,要在运行时才能计算。参数必须是字符型指针 const char*(char*能转换为const char*)。当数组名作为参数传入时,实际上数组就退化成指针了。
它的功能是:返回字符串的长度。该字符串可能是自己定义的,也可能是内存中随机的,该函数实际完成的功能是从代表该字符串的第一个地址开始遍历,直到遇到结束符NULL。返回的长度大小不包括NULL。

2、sizeof(…)是运算符,vs2015中typedef为unsigned long long,其值在编译时即计算好了,参数可以是数组、指针、类型、对象、函数等。

它的功能是:获得保证能容纳实现所建立的最大对象的字节大小。由于在编译时计算,因此sizeof不能用来返回动态分配的内存空间的大小。实际上,用sizeof来返回类型以及静态分配的对象、结构或数组所占的空间,返回值跟对象、结构、数组所存储的内容没有关系。

具体而言,当参数分别如下时,sizeof返回的值表示的含义如下:

  • 数组——编译时分配的数组空间大小;
  • 指针——存储该指针所用的空间大小(存储该指针的地址的长度,是长整型,32位系统应该为4,64位系统为8);
  • 类型——该类型所占的空间大小;
  • 对象——对象的实际占用空间大小;
  • 函数——函数的返回类型所占的空间大小。函数的返回类型不能是void。

实例:

    string s("hiyo");
    char cstring[] = "hiyo";
    const char* cs = "hiyo";

    cout << strlen(s.c_str()) << endl; //c_str()返回指向c风格字符串的指针
    cout << s.size() << endl;  //string类size()接口
    cout << sizeof(s) << endl; //string类对象的大小,与具体内容无关,与具体实现有关,这是vs2015下 
    cout << sizeof(s.c_str()) << endl; //指针变量本身大小
    cout << strlen(cstring) << endl;//字符串自身长度
    cout << sizeof(cstring) << endl;//字符数组大小,包含隐藏的空字符
    cout << strlen(cs) << endl;//字符串自身大小
    cout << sizeof(cs) << endl;//指针大小

运行结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_38216239/article/details/80522403