sizeof, strlen及其它

sizeof是运算符,strlen()是函数。

对于数组A,sizeof(A)求得数组所占内存的大小;

对于指向A的指针p,sizeof(*p)求得数组第一个元素的大小;

	int A[] = { 1,2,3,4,5 };
	int sizeof_A = sizeof(A);
	cout << "size of A: " << sizeof_A << endl;

	char B[] = { 'a', 'b', 'c', 'd', 'e' };
	int sizeof_B = sizeof(B);
	cout << "size of B: " << sizeof_B << endl;

	char C[] = "abcde";
	int sizeof_C = sizeof(C);
	cout << "size of C: " << sizeof_C << endl;

	int *p1 = A;
	int sizeof_star_p1 = sizeof(*p1);
	cout << "size of *p1: " << sizeof_star_p1 << endl;

	int sizeof_p1 = sizeof(p1);
	cout << "size of p1: " << sizeof_p1 << endl;

	char *p2 = B;
	int sizeof_star_p2 = sizeof(*p2);
	cout << "size of *p2: " << sizeof_star_p2 << endl;

	int sizeof_p2 = sizeof(p2);
	cout << "size of p2: " << sizeof_p2 << endl;
输出:


strlen()求得从给定内存处到第一个'\0'的长度

	int strlen_B = strlen(B);
	cout << "strlen of B: " << strlen_B << endl;

	int strlen_C = strlen(C);
	cout << "strlen of C: " << strlen_C << endl;

	int strlen_p2 = strlen(p2);
	cout << "strlen of p2: " << strlen_p2 << endl;

	char *p3 = C;
	int strlen_p3 = strlen(p3);
	cout << "strlen of p3: " << strlen_p3 << endl;
输出:



-----------------------------------------------补充1---------------------------------------------------------------------

int main()
{
	int a[5] = { 1,2,3,4,5 };
	int *p = (int *)(&a + 1);
	printf("%d, %d\n", *(a + 1), *(p - 1));

	system("pause");
	return 0;
}

结果:



-----------------------------------------------补充2---------------------------------------------------------------------

数组名作为参数传递时,数组名退化为指针,因此需要同时传递数组大小。

<pre name="code" class="cpp">void example(char acWelcome[]) {
	printf("%d", sizeof(acWelcome));
	return;
}
int main() {
	char acWelcome[] = "Welcome to Huawei Test";
	example(acWelcome);

	printf("\n%d\n", sizeof(acWelcome));

	system("pause");
	return 0;
}

 

结果:




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值