【C语言学习笔记】之sizeof

代码1:

#include <stdio.h>

int main() {
	char *str = "GeeksQuiz";
	char str1[] = "GeeksQuiz";
	char str2[] = { 'G', 'e', 'e', 'k', 's', 'Q', 'u', 'i', 'z' };
	int n = sizeof(str) / sizeof(str[0]); //4, str是一个指针
	int n1 = sizeof(str1) / sizeof(str1[0]); //10, str1是一个数组,注意'\0'
	int n2 = sizeof(str2) / sizeof(str2[0]); //9,数组,

	printf("n = %d, n1 = %d, n2 = %d", n, n1, n2);

	return 0;
}

笔记:

In main, the name array is an array so you get the size in bytes of the array with sizeof. 

However, an array decays to a pointer when passed to a function, so you get sizeof(int*) inside the function.

代码2:

#include<stdio.h>
/*数组名当函数参数传递时,会被当做指针处理*/
void func1(int a[]) {
	printf("%d\n",sizeof(a)); // 4
}

void func2(int *a) {
	printf("%d\n", sizeof(a));
}
int main() {
	int array[] = { 1, 2, 3 };
	printf("%d\n", sizeof(array)); // 12
	func1(array);//4
	func2(array);//4
	return 0;
}

参考: http://stackoverflow.com/questions/9509829/c-size-of-array



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值