sizeof/strlen小论

sizeof这个函数的用法,你真的懂吗,不见得吧。上一段代码看一下就知道了:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 void Founc(char str1[100])
 5 {
 6     cout<<sizeof(str1)<<endl;
 7 }
 8 
 9 int main( void )
10 {
11     char str[] = "hello";
12     char ch[100]="world";
13     char *p = str;
14     int n=10;
15     cout<<sizeof(str)<<" "<<sizeof(p)<<" "<<sizeof(n)<<" "<<sizeof(ch)<<endl;
16     Founc(str);
17     void *p1=malloc(100);
18     cout<<sizeof(p1)<<endl;
19     return 0;
20 }


这段程序的结果是:

6 4 4  100

4

4

你答对了吗?

注意指针类型在32位系统中占4个字节。

strlen与sizeof的区别

  1.从功能定义上,strlen函数,用来求字符串的长度,sizeof函数是用来求指定变量或变量类型等所占用内存的大小;

  2.sizeof是运算符,而strlen是C库函数strlen只能用char*做参数,且以'/0'结尾的;

  对于静态数组处理:

     char str[20]="0123456789";

     strlen(str)=10;   //表示数组中字符串的长度

     sizeof(str)=20;   //表示数组变量分配的长度

  对于指针处理:

     char *str="0123456789";

     strlen(str)=10;     //表示字符串的长度

     sizeof(str)=4;      //表示指针变量的所占内存大小

     sizeof(*str)=1;     //表示'0'这个字符变量的所占内存大小

原文地址:https://www.cnblogs.com/sjlove/p/3061489.html