C sizeof() 与 strlen()

来源:互联网 发布:只有我知2 完整版高清 编辑:程序博客网 时间:2024/04/24 14:38

在C语言中有两个计算长度的函数sizeof() 与 strlen(),今天就来讲讲他们的不同。

sizeof 是C语言的内置运算符,以字节为单位给出指定类型的大小。通常使用%zd转换说明匹配sizeof的返回类型。

strlen()给出字符串中的字符长度。因为1字节存储1个字符,大家可能认为把两种方法应用与字符串得到的结果相同,但事实并非如此,大家看一下下面的程序。

#include<stdio.h>
#include<string.h>/*提供strlen()函数的原型*/
#define PRAISE "You are an extraordinary being."
int main()
{
char name[40];
printf("What's your name? ");
scanf("%s", name);
printf("Hello, %s. %s\n", name, PRAISE);
printf("Your name of %zd letters occupies %zd memory cells.\n",
strlen(name), sizeof(name));
printf("The phrase of praise has %zd letters", strlen(PRAISE));
printf(" and occupies %zd memory cells.\n", sizeof PRAISE);
return 0;
}

输入你的名字你将得到结果如下:

What's your name? wangjian
Hello, wangjian. You are an extraordinary being.
Your name of 8 letters occupies 40 memory cells.
The phrase of praise has 31 letters and occupies 32 memory cells.
请按任意键继续....

sizeof 运算符报告,name数组有40个存储单元。但是,只有前8个单元来存储wangjian,所以strlen()得出的结果是8.

name数组的第9个单元存储空字符,strlen()并为将其计入。

对于PRAISE,用strlen()得出的字符串中的字符串(包括空格和标点符号)。然而,sizeof运算符给出的数更大,应为它把字符串末尾不可见的空字符也计算在内。该程序并未明确告诉计算机要给字符串预留多少空间,所以它

必须计算双引号内的字符数。

可见strlen()用来计算字符串中的字符个数,不包括\0。sizeof()函数来计算对象的字节长度。

0 0
原创粉丝点击