strlen和sizeof的区别

基本含义

sizeof()实际上是一个单目运算符,计算括号内对象的内存大小。
strlen()是求括号内字符串、以括号内地址为首址的字符串为首址,下一个“\0”为结束标志的长度。

strlen()以“\0”为结束标志

尤其是在没有指定大小的字符型数组中,以“string”方式赋值给字符数组时会自动在末尾加入“\0”,以‘a’单个字符方式赋值时不会在末尾加上“\0”,所以:

例子1

#include <iostream>
using namespace std;
int main() {
	char a0[] = { "hello" };
	char a1[] = { "hel\0lo" };
	char a[12] = { "hel\0lo" };	
	char b0[] = { 'h','e','l','l','o' };//警告:可能没有为字符串‘b0’添加字符串零终止符
	char b1[] = { 'h','e','l','l','o', '\0' };
	char b[12] = { 'h','e','l','l','o','\0' };
	cout <<"a0:\t" << "[strlen] " << strlen(a0) << "\t[sizeof] " << sizeof(a0) << endl;
	cout << "a1:\t" << "[strlen] " << strlen(a1) << "\t[sizeof] " << sizeof(a1) << endl;
	cout << "a:\t" << "[strlen] " << strlen(a) << "\t[sizeof] " << sizeof(a) << endl;
	cout << "b0:\t" << "[strlen] " << strlen(b0) << "\t[sizeof] " << sizeof(b0) << endl;
	cout << "b1:\t" << "[strlen] " << strlen(b1) << "\t[sizeof] " << sizeof(b1) << endl;
	cout << "b:\t" << "[strlen] " << strlen(b) << "\t[sizeof] " << sizeof(b) << endl;
	return 0;
}

运行结果:

a0:     [strlen] 5      [sizeof] 6
a1:     [strlen] 3      [sizeof] 7
a:      [strlen] 3      [sizeof] 12
b0:     [strlen] 37     [sizeof] 5
b1:     [strlen] 5      [sizeof] 6
b:      [strlen] 5      [sizeof] 12

另外(转义字符相关)

	char c[] = { "ab\\\0c" };
	cout<< "[strlen] " << strlen(c) << "\t[sizeof] " << sizeof(c) << endl;

	char d[] = { "abc" };
	cout << "[strlen] " << strlen(d) << "\t[sizeof] " << sizeof(d) << endl;

运行结果:

[strlen] 3      [sizeof] 6
[strlen] 3      [sizeof] 4

例子2

#include <iostream>
using namespace std;
int main() {
	char c[] = { "ab\\\\0c" };
	cout<< "[strlen] " << strlen(c) << "\t[sizeof] " << sizeof(c) << endl;
	for (int i = 0; i < sizeof(c); i++) {
		cout << "c[" << i << "] = " << c[i] << "\t";
	}

	cout << endl;

	char c1[] = { "ab\\\0c" };
	cout << "[strlen] " << strlen(c1) << "\t[sizeof] " << sizeof(c1) << endl;
	for (int i = 0; i < sizeof(c1); i++) {
		cout << "c1[" << i << "] = " << c1[i] << "\t";
	}

	cout << endl;

	char d[] = { "abc" };
	cout << "[strlen] " << strlen(d) << "\t[sizeof] " << sizeof(d) << endl;
	return 0;
}

运行结果:

[strlen] 6      [sizeof] 7
c[0] = a        c[1] = b        c[2] = \        c[3] = \        c[4] = 0        c[5] = c        c[6] =
[strlen] 3      [sizeof] 6
c1[0] = a       c1[1] = b       c1[2] = \       c1[3] =         c1[4] = c       c1[5] =
[strlen] 3      [sizeof] 4
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值