strlen与sizeof 的基本用法

简介: strlen与sizeof 的基本用法



1. sizeof

sizeof 运算符用于获取数据类型、变量或表达式所占用的内存大小(以字节为单位)。

1.2 基本用法

获取类型长度

size_t sizeof_datatype = sizeof(type);

获取变量长度

size_t sizeof_variable = sizeof(variable);

示例用法:

1.2.1 获取数据类型的大小:

#include <iostream>
using namespace std;
int main()
{
    cout<<sizeof(int)<<endl;//4
    cout<<sizeof(char)<<endl;//1
    cout<<sizeof(double)<<endl;//8
    return 0;
}

1.2.2 获取变量的大小:

#include <iostream>
using namespace std;
int main()
{
    int x;
    size_t x_size = sizeof(x);
    cout<<x_size<<endl;//4
    int buffer[100];
    size_t buffer_size = sizeof(buffer);
    cout<<buffer_size<<endl;//400
    size_t buffer_size2 = sizeof(buffer[0]);
    cout<<buffer_size2<<endl;//4
    return 0;
}

1.2.3 获取表达式的大小:

#include <iostream>
using namespace std;
int main()
{
    size_t expr_size = sizeof(1 + 2.0);
    cout<< expr_size<<endl;//8
    return 0;
}

1.2.4 我一般这样用的最多:

#include <iostream>
using namespace std;
int main()
{
    int arr[100];
    int n=sizeof(arr) / sizeof(arr[0]);//存储arr的数组大小
    return 0;
}

2. strlen

strlen用于计算一个以null终止字符数组(即C字符串)的长度,也就是字符串中字符的数量,但不包括字符串结尾的null字符 ('\0'),即hello长度就是5.

使用该函数需要导入库函数

#include <string.h>

示例

#include <stdio.h>
#include <string.h>
int main() {
    const char *str = "Hello";
    size_t length = strlen(str);
    printf("字符串 \"%s\" 的长度是 %zu\n", str, length);//字符串 "Hello" 的长度是 5
    return 0;
}
目录
相关文章
|
4天前
|
编译器 C语言
sizeof,sizeof与strlen的区别
sizeof,sizeof与strlen的区别
10 0
sizeof,sizeof与strlen的区别
|
2月前
|
存储 安全 编译器
C/C中sizeof和strlen函数的实现:详细解析sizeof和strlen函数的实现机制、参数说明和使用技巧
C/C中sizeof和strlen函数的实现:详细解析sizeof和strlen函数的实现机制、参数说明和使用技巧
20 1
|
5月前
|
Serverless
sizeof和strlen的区别【详解】
sizeof和strlen的区别【详解】
30 0
|
5月前
|
C语言
strlen和sizeof的区别
strlen和sizeof的区别
39 0
|
5月前
strlen与sizeof的区别
strlen与sizeof的区别
22 0
|
7月前
|
存储
指针进阶(3) -- 关于sizeof和strlen的详细总结(下)
指针进阶(3) -- 关于sizeof和strlen的详细总结(下)
|
7月前
指针进阶(3) -- 关于sizeof和strlen的详细总结(上)
指针进阶(3) -- 关于sizeof和strlen的详细总结(上)
|
7月前
|
存储
指针进阶(3) -- 关于sizeof和strlen的详细总结(中)
指针进阶(3) -- 关于sizeof和strlen的详细总结(中)
|
8月前
sizeof与strlen区别
sizeof是关键字,参数可以是各种数据(包括函数,类型,对象,数组,指针……)用于计算数据所占字节大小 strlen是函数,参数类型必须是字符型指针(char *),用于计算字符串,从字符串的第一个地址开始遍历,直到遇到‘\0’停止
46 0
|
机器学习/深度学习 C语言
sizeof与strlen的区别和详解
sizeof与strlen的区别和详解