sizeof, strlen及其它
2016-02-16 09:34
267 查看
sizeof是运算符,strlen()是函数。
对于数组A,sizeof(A)求得数组所占内存的大小;
对于指向A的指针p,sizeof(*p)求得数组第一个元素的大小;
strlen()求得从给定内存处到第一个'\0'的长度
-----------------------------------------------补充1---------------------------------------------------------------------
结果:
-----------------------------------------------补充2---------------------------------------------------------------------
数组名作为参数传递时,数组名退化为指针,因此需要同时传递数组大小。
结果:
对于数组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; }
结果:
相关文章推荐
- 组合索引
- 强化对齐唤醒机制?
- MySQL关键性能监控(QPS/TPS)
- 警告: 未提供 -tsa 或 -tsacert, 此 jar 没有时间戳。如果没有时间戳, 则在签名者证书的到期
- BZOJ4407: 于神之怒加强版
- IOS视图隐藏UItabBar
- DevExpress自学笔记—整体修改窗体及控件的皮肤样式2
- MIUI7 SYSTEM 优化些啥
- ORACLE中的自治事务 PRAGMA AUTONOMOUS_TRANSACTION
- xml
- Hadoop MapReduce示例代码
- xml
- 以前写的比较实用的mysql代码[3]从一段话中获得关键信息
- 字符串转整数或浮点数
- 【React Native开发】React Native控件之RefreshControl组件详解(21)
- 1407: [Noi2002]Savage 扩展欧几里得算法
- js 只能输入正浮点数和整数
- SSM三大框架整合详细教程(Spring+SpringMVC+MyBatis)
- zxing扫描二维码和识别图片二维码及其优化策略
- CocoaPods的安装使用