strlen和sizeof在c语言中的用法
时间: 2023-12-20 21:32:26 浏览: 99
在C语言中,strlen和sizeof是两个常用的函数,用于获取字符串长度和计算数据类型的大小。
1. strlen函数用于获取字符串的长度,即字符串中字符的个数,不包括字符串末尾的空字符'\0'。它的原型定义在<string.h>头文件中,函数的返回值是一个无符号整数。
```c
#include <stdio.h>
#include <string.h>
int main() {
char* str = "abcdef";
printf("Length of str: %d\n", strlen(str)); // 输出:6
return 0;
}
```
这段代码中,strlen函数被用来获取字符串"abcdef"的长度,即6个字符。
2. sizeof运算符用于计算数据类型或变量的大小,以字节为单位。它可以用于任何数据类型,包括基本数据类型、数组、结构体等。sizeof的结果是一个整数常量,可以在编译时确定。
```c
#include <stdio.h>
int main() {
int a = 4;
printf("Size of int: %d\n", sizeof(int)); // 输出:4
printf("Size of a: %d\n", sizeof(a)); // 输出:4
return 0;
}
```
这段代码中,sizeof运算符被用来计算int类型的大小,结果是4个字节。
阅读全文
相关推荐


















