sizeof和strlen本质区别
sizeof定义
sizeof 运算符。表达式 sizeof(type) 得到某个类型或某个变量在特定平台上的准确存储大小,返回值unsigned int 类型
strlen定义
strlen是个函数,函数原型:size_t strlen(const char *str),用来计算字符串的实际长度(不包括‘\0'在内),函数的返回值size_t 为unsigned int 类型,
例子:
#include#include #include<string.h> #define PI 3.14159265 const int b = 50000; int main(void) { char a[] = "hello world"; int *c ="asfdgh"; unsigned int d = sizeof(c); printf("%ld,%ld,%ld,%ld",sizeof(c),strlen(c),sizeof(a),strlen(a)); return 0; }
运行结果:
8 6 12 11
int * 在64位操作系统内存空间是8byte,所以sizeof(a)=8
总结:
字符串在计算机内存中存储时,系统会自动添加一个‘/0'作为字符串结束符,sizeof 计算结果包括’\0'在内,而strlen 计算结果遇到‘/0'就结束,计算的结果不包括’/0';