现在的位置: 首页 > 综合 > 正文

【C语言天天练(五)】strlen和sizeof

2018年05月02日 ⁄ 综合 ⁄ 共 1332字 ⁄ 字号 评论关闭

引言:


sizeof运算符,它以字节为单位给出数据的大小。

strlen()函数以字符为单位给出字符串的长度。

从上面可以明确的看出来,sizeof是运算符,而strlen则是函数。


一、sizeof

sizeof的参数有很多,比如数据类型(int、float等)、数组(数组作为参数时要使用数组名)、指针、结构体、对象、函数等等。

数组——编译时分配的数组空间大小。

指针——存储该指针所用的空间大小(存储该指针的地址的长度,是长整型,一般为4)。

类型——该类型所占空间大小。

对象——对象的实际占用空间大小。

函数——函数的返回类型所占的空间大小。函数的返回类型不能是void。


二、strlen()

strlen是函数,要在运行时才能计算。其参数必须是字符型指针(char *),且必须是以‘\0’结尾的。当数组名作为参数传入时,实际上数组名以退化为指针。

它的功能是:返回字符串的长度。该字符串可能是自己定义的,也可能是内存中随机的,该函数实际完成的功能是从代表该字符串的第一个地址开始遍历,直到遇到结束符'\0'。返回的长度大小不包括'\0'。

三、示例

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

char *s = "libing";
char array[10] = "libing";
int i;
unsigned long l;
unsigned short sh;
long long ll;

int
main(void)
{
	int len;
	printf("sizeof test:\n");
	len = sizeof(s);
	printf("the length of s = %d\n", len);
	len = sizeof(array);
	printf("the length of array[10] = %d\n", len);
	len = sizeof(int);
	printf("the length of int = %d\n", len);
	len = sizeof(unsigned long);
	printf("the length of unsigned long = %d\n", len);
	len = sizeof(long long);
	printf("the length of long long = %d\n", len);
	len = sizeof(unsigned short);
	printf("the length of unsigned short = %d\n\n", len);

	printf("strlen test:\n");
	len = strlen(s);
	printf("the length of s = %d\n", len);
	len = strlen(array);
	printf("the length of array[10] = %d\n", len);
	return 0;
}

输出结果如下:

sizeof test:
the length of s = 4
the length of array[10] = 10
the length of int = 4
the length of unsigned long = 4
the length of long long = 8
the length of unsigned short = 2

strlen test:
the length of s = 6
the length of array[10] = 6

抱歉!评论已关闭.