sizeof和strlen的区别及使用详解
详细见链接:
https://blog.youkuaiyun.com/magic_world_wow/article/details/80500473
首先我们来看一下sizeof和strlen的区别:
sizeof操作符的结果类型为size_t(The sizeof keyword gives the amount of storage, in bytes, associated with a variable or a type (including aggregate types). This keyword returns a value of type size_t.)(它在头文件用typedfe定义为unsigned int类型),计算的是分配空间的实际字节数。strlen结果类型也为size_t(size_t strlen( const char *string )),但strlen是计算的空间中字符的个数(不包括‘\0’)。
sizeof是运算符,可以以类型、函数、做参数 。strlen是函数,只能以char*(字符串)做参数。而且,要想得到的结果正确必须包含 ‘\0’(通过strlen的实现得知)。
sizeof是在编译的时候就将结果计算出来了是类型所占空间的字节数,所以以数组名做参数时计算的是整个数组的大小。而strlen是在运行的时候才开始计算结果,这是计算的结果不再是类型所占内存的大小,数组名就退化为指针了。
另外,sizeof不能计算动态分配空间的大小如: