【1】strlen 与 sizeof的区别
(1)sizeof操作符的返回结果类型是size_t。size_t在头文件中typedef为 unsigned int类型,该类型保证能容纳实现所建立的最大对象的字节大小。
(2)sizeof是操作符,strlen是函数。
(3)sizeof可用类型或变量作参数,strlen只能用char*作参数,且必须是以“\0”结尾的。
(4)数组名作为sizeof的参数不退化,传递给strlen就退化为指针了。
(5)编译器在编译时就把sizeof计算过了。编译时类型或变量的长度已确定,这正是sizeof(x)可以定义数组维数的原因。
示例代码如下:
1 #include<iostream>
2 using namespace std;
3
4 void main()
5 {
6 // 例1:
7 char* ps = "0123456789";
8 cout << sizeof(ps) << endl; //4, ps是指向字符串常量的字符指针,指针占用4个字节。
9 cout << sizeof(*ps) << endl; //1, *ps是第一个字符即“0”,字符占用1个字节。
10 cout << strlen(ps) << endl << endl; //10, 常量字符串的长度。除过标识符“\0”,有效字符长度为10个。
11 // 例2:
12 char cs[] = "0123456789";
13 cout << sizeof(cs) << endl; //11, cs是数组类型,计算到“\0”位置,因此占用内存大小为(10*1 + 1 = 11)。
14 cout << sizeof(*cs) << endl; //1, *cs是第一个字符即“0”,字符占用1个字节。
15 cout << strlen(cs) << endl << endl; //10, cs字符数组的长度。除过标识符“\0”,有效字符长度为10个。
16 // 例3:
17 char as[100] = "0123456789";
18 cout << sizeof(as) << endl; //100, as是数组类型,在内存中分配的大小,100*1。
19 cout << strlen(as) << endl << endl; //10,strlen计算字符串的长度,直到“\0”为止。有效字符长度为10个。
20 // 例4:
21 int ns[100] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
22 cout << sizeof(ns) << endl << endl; //400, ns时数组类型,在内存中的大小,100*4。
23 // strlen(ns) 错误! strlen的参数只能是char*,且必须是以“\0”结尾的字符串。
24 // 例5:
25 cout << sizeof("hello,world!") << endl; //13 在内存中占用13个字节
26 cout << strlen("hello,world!") << endl << endl; //12 理解与sizeof值的差异原因
27
28 system("pause");
29 }
30 // run out
31 /*
32 4
33 1
34 10
35
36 11
37 1
38 10
39
40 100
41 10
42
43 400
44
45 13
46 12
47
48 请按任意键继续. . .
49 */
(6)函数strlen是用来计算字符串的实际长度,其结果在程序运行的时才能计算出来。
(7)操作符sizeof如果用于类型必须加括弧,如果用于变量名可以不加括弧。
示例代码:
1 #include<iostream>
2 using namespace std;
3
4 void main()
5 {
6 char ch;
7 int nValue;
8 cout << sizeof ch << endl; //1, 直接用于变量名,char类型占一个字节
9 cout << sizeof nValue << endl; //4, 直接用于变量名,int类型占4个字节
10 system("pause");
11 }
12 // run out
13 /*
14 1
15 4
16 请按任意键继续. . .
17 */
(8)数组名作为实参传给函数时,实质传的是指针而不是数组,传递的是数组的首地址。
示例代码如下:
1 #include<iostream>
2 using namespace std;
3
4 void fun(int ar[])
5 {
6 cout << sizeof(ar) << endl;
7 }
8
9 void main()
10 {
11 int arrayInt[5] = {1, 2, 3, 4, 5};
12 fun(arrayInt); // 4
13 system("pause");
14 }
在C++里参数传递数组永远都是传递指向数组首元素的指针,编译器不知道数组的大小。
另外,sizeof操作符可以用于确定数组可以容纳元素的个数。
示例代码如下:
1 #include<iostream>
2 using namespace std;
3
4 void main()
5 {
6 int nArray[] = {1, 2, 3, 4, 5};
7 cout << sizeof(nArray) / sizeof(typeid(nArray[0]).name()) << endl; // 5
8 system("pause");
9 }
Good Good Study, Day Day Up.
顺序 选择 循环 总结
原文链接: https://www.cnblogs.com/Braveliu/archive/2013/01/01/2841521.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/74292
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!