sizeof和strlen的区别

来源:互联网 发布:软件培训老师 编辑:程序博客网 时间:2024/06/13 10:46

示例:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>


void fun(char str[100])
{
printf("%d\n",sizeof(str));
}


int main()
{
char str[]="hello";
char *p1=str;
int n=10;
char *p2=(char*)malloc(100);


printf("%d\n",sizeof(str));
printf("%d\n",strlen(str));


printf("%d\n",sizeof(p1));
printf("%d\n",strlen(p1));


printf("%d\n",sizeof(n));
printf("%d\n",sizeof(p2));
fun(p2);
}


//分析如下:

第一个printf语句:sizeof()的值包含字符串最后的一个终结符'\0'。所以为6

第二个printf语句:strlen()的值不包含字符串最后的一个终结符'\0'。所以为5

第三个printf语句:由于p1是一个指针,因为系统是32位的系统,所以值为4,即为4个字节

第四个printf语句:和第二个printf语句相同

第五个printf语句:因为int类型的数据占4个字节,所以值为4

第六个printf语句:用来获得指针所占的字节数目,和第三个一样,值为4

调用fun函数:数组作为函数的参数时,对系统来说,char *str[100]和char *str是一样的,值为4


原创粉丝点击