sizeof strlen

本文通过多个示例详细探讨了C++中不同类型的字符数组和字符串的sizeof与strlen函数的区别,包括数组作为函数参数时的行为变化。此外,还讨论了类的大小计算以及数组元素计数的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


char c[] = "abcde";
cout << sizeof(c)<<endl; //output 6
cout << strlen(c) << endl;//output 5
------------------------------------------------
char c[10] = "abcde";
cout << sizeof(c)<<endl; //output 10
cout << strlen(c) << endl;//output 5
------------------------------------------------
//数组作为参数传给函数时传的是指针而不是数组,传递的是数组的首地址
char c[10] = "abcde";
void Print(char ch[])//等价于 fun(char *)
{	
	cout << sizeof(ch) << endl; //output 4
	cout << strlen(ch) << endl;//output 5
}
void Print(char ch[5])//等价于 fun(char *)
{	
	cout << sizeof(ch) << endl; //output 4
	cout << strlen(ch) << endl;//output 5
}
void Print(char* ch)
{	
	cout << sizeof(ch) << endl; //output 4
	cout << strlen(ch) << endl;//output 5
}
------------------------------------------------
char*c = "abcde";
cout << sizeof(c)<<endl;//output 4 (pointer)
cout << strlen(c) << endl;//output 5
------------------------------------------------
int i[4];
cout << sizeof(i)<<endl; //output 16
cout << sizeof(i)/sizeof(i[0])<<endl;//output 4
------------------------------------------------
char Array[3] = {'0'};
sizeof(Array) == 3;
char *p = Array;
strlen(p) == 1;//sizeof(p)结果为4
------------------------------------------------
char c[]="a\n";
cout << sizeof(c) << endl;//output 3  //'\n' is one char
cout << strlen(c) << endl;//output 2  //'\n' is one char
------------------------------------------------
class X
{ int i; int j; char k;};
X x;
cout<<sizeof(X)<<endl; //结果 12 (内存补齐)
cout<<sizeof(x)<<endl; //结果 12 同上
------------------------------------------------
char c[5] = "abcde"; //error
------------------------------------------------


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值