C++(C)中Sizeof与Strlen的区别
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C++(C)中Sizeof与Strlen的区别,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2004字,纯文字阅读大概需要3分钟。
内容图文
C++(C)中Sizeof与Strlen的区别
一、知识总结:
1、sizeof
(1)、使用方法
sizeof为运算符
sizeof unary-expression
sizeof ( type-name )
(2)、运行阶段
sizeof在编译时计算。
(3)、返回值
sizeof:获取对象所分配的字节大小。
用sizeof来返回类型以及静态分配的对象、结构或数组所占的空间,返回值跟对象、结构、数组所存储的内容没有关系。
具体而言,当参数分别如下时,sizeof返回的值表示的含义如下:
数组——编译时分配的数组空间大小;
指针——存储该指针所用的空间大小(存储该指针的地址的长度,是长整型,应该为4);
类型——该类型所占的空间大小;
对象——对象的实际占用空间大小;
函数——函数的返回类型所占的空间大小。函数的返回类型不能是void。
2、strlen
(1)、使用方法
strlen为函数
size_t strlen( const char *string ); // 返回值为size_t ,即unsignedint
(2)、运行阶段
strlen在运行阶段阶段。
Libraries
Allversions of the C run-time libraries.
(3)、返回值
strlen返回(自定义或内存中随机)字符串的实际长度,不包括NULL。
从代表该字符串的第一个地址开始遍历,直到遇到结束符NULL。
二、Dem程序:
//主题:strlen()与sizeof相关的调研
// 参考:http://www.cnblogs.com/carekee/articles/1630789.html #include <iostream> #include <cstring> using namespace std; void test1(); void test2(char *p); int main(void) { test1(); cout<<endl; char sz[10]; cout<<"strlen(sz)="<<strlen(sz)<<endl; cout<<"sizeof(sz)="<<sizeof(sz)<<endl; cout<<endl; test2(sz); } void test1() { cout<<"In test1():"<<endl; //char gz[10] = "12"; char gz[10]; cout<<"strlen(gz)="<<strlen(gz)<<endl; cout<<"sizeof(gz)="<<sizeof(gz)<<endl; cout<<endl; char *pch = new char[10]; cout<<"strlen(pch)="<<strlen(pch)<<endl; // 输出未定。因为这取决于pch存了什么值(从[0]直到遇到第一个NULL为止 cout<<"sizeof(pch)="<<sizeof(pch)<<endl; //cout<<"strlen(*pch)="<<strlen(*pch)<<endl; // [ERROR]IntelliSense: "char" 类型的实参与 "const char *" 类型的形参不兼容 // [ERROR]error C2664: “strlen”: 不能将参数 1 从“char”转换为“const char *” cout<<"sizeof(*pch)="<<sizeof(*pch)<<endl; } void test2(char *p) { cout<<"In test2():"<<endl; cout<<"strlen(p)="<<strlen(p)<<endl; cout<<"sizeof(p)="<<sizeof(p)<<endl; }
三、参考资料:
1、http://www.cnblogs.com/carekee/articles/1630789.html
原文:http://blog.csdn.net/caoyingsdhzcx/article/details/41518561
内容总结
以上是互联网集市为您收集整理的C++(C)中Sizeof与Strlen的区别全部内容,希望文章能够帮你解决C++(C)中Sizeof与Strlen的区别所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。