由strlen和sizeof引起的思考
作者:互联网
strlen 函数
std::size_t strlen( const char* str );
- 返回给定字符串的长度,即从
str
指向的首元素到以首个空字符\0
结尾的字符串的字符数,注意:不包含\0
。
sizeof 运算符
- 查询对象或类型的大小。即求数据类型所占的空间大小。
语法
- sizeof(
表达式(expression)或类型(type)
),获得表达式(expression)或类型(type)
的对象表示的字节数。 - sizeof
表达式(expression)
,获得表达式(expression)
的类型的对象表示的字节数。
sizeof a; //正确
sizeof int;//错误
思考
1
- strlen不计入
\0
const char str[] = "How";
std::cout << "without null character: " << std::strlen(str) << '\n'
<< "with null character: " << sizeof str << '\n';
/*
without null character: 3
with null character: 4
*/
2
- str与str2不同。str为维度为4的数组,只是初始化时未显式定义长度;
- str2为指针,所有
sizeof str2
实际是计算指针所占的空间大小,在64位系统下为8个字节。
const char str[] = "How";
const char* str2 = "How";
std::cout << "strlen of str: " << std::strlen(str) << '\n'
<< "strlen of str2: " << std::strlen(str2) << '\n';
std::cout << "sizeof of str: " << sizeof str << '\n'
<< "sizeof of str2: " << sizeof str2 << '\n';
/*
strlen of str: 3
strlen of str2: 3
sizeof of str: 4
sizeof of str2: 8
*/
3
- strlen统计字符串实际长度,sizeof查询分配空间大小。
char str3[10]="How";
只能加9个字符,因为还要留一个给\0
.
char str3[10]="How";
std::cout << "strlen of str3: " << std::strlen(str3) << '\n'
<< "sizeof of str3: " << sizeof(str3) << '\n';
/*
strlen of str3: 3
sizeof of str3: 10
*/
标签:const,思考,char,How,str,sizeof,strlen 来源: https://www.cnblogs.com/nuo-chen/p/16335538.html