C语言中字符串的strlen()和sizeof()区别
strlen()
strlen()函数是C语言中的一个预定义函数,声明在“string.h”头文件中。它用于获取数组或字符串的长度。
以下是C语言中strlen()函数的语法:
size_t strlen(const char *string);
其中:
string − 需要计算长度的字符串。
以下是一个C语言中strlen()函数的示例:
示例
#include <stdio.h>
#include <string.h>
int main () {
char s1[10] = "Hello";
int len ;
len = strlen(s1);
printf("Length of string s1 : %d
", len );
return 0;
}输出
Length of string s1 : 10
在上面的示例中,一个字符型数组s1被初始化为一个字符串,变量len存储s1的长度。
char s1[10] = "Hello"; int len ; len = strlen(s1);
sizeof()
sizeof()函数是C语言中的一个一元运算符,用于获取任何类型数据的以字节为单位的大小。
以下是C语言中sizeof()函数的语法:
sizeof( type );
其中:
type − 任何你想要计算大小的类型、数据类型或变量。
以下是一个C语言中sizeof()函数的示例:
示例
#include <stdio.h>
int main() {
int a = 16;
printf("Size of variable a : %d
",sizeof(a));
printf("Size of int data type : %d
",sizeof(int));
printf("Size of char data type : %d
",sizeof(char));
printf("Size of float data type : %d
",sizeof(float));
printf("Size of double data type : %d
",sizeof(double));
return 0;
}输出
Size of variable a : 4 Size of int data type : 4 Size of char data type : 1 Size of float data type : 4 Size of double data type : 8
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP