其他分享
首页 > 其他分享> > 由strlen和sizeof引起的思考

由strlen和sizeof引起的思考

作者:互联网

strlen 函数

std::size_t strlen( const char* str );

sizeof 运算符

语法

sizeof a; //正确
sizeof int;//错误

思考

1

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

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

	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