当前位置:网站首页>strlen跟sizeof区别
strlen跟sizeof区别
2022-07-30 12:51:00 【qq_25427995】
关于 strlen 与 sizeof 的区别:
strlen 是函数,sizeof 是运算符。
strlen 测量的是字符的实际长度,以’\0’ 结束(不包含’\0’ )。而sizeof 测量的是字符的分配大小,如果未分配大小,则遇到’\0’ 结束(包含’\0’ ,也就是strlen测量的长度加1),如果已经分配内存大小,返回的就是分配的内存大小。
比如:
char str[] = “Hello World”;
char str1[100] = “Hello World”;
cout << strlen(str) << endl;
cout << sizeof(str) << endl;
cout << sizeof(str1) << endl;
3.但是在子函数中,ziseof 会把从主函数中传进来的字符数组当作是指针来处理。指针的大小又是由机器来决定,而不是人为的来决定的。
#include
#include
#include
using namespace std;
void fun(char str[10])
{
cout << sizeof(str) << endl;
}
int main()
{
char str[] = “Hello World”;
fun(str);
return 0;
}
4.我们知道字符数组的初始化一次性赋值,也可以逐个赋值。可以指定数组的大小,也可以不指定数组长度。
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = “hello”;
char str2[] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};
char str3[] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’};
printf("str1:%s\n",str1);
printf("str2:%s\n",str2);
printf("str3:%s\n",str3);
printf("str1:%d\n", strlen(str1));
printf("str2:%d\n", strlen(str2));
printf("str3:%d\n", strlen(str3));
return 0;
}
这是为什么呢?
我们知道字符串是以 ‘\0’ 为结束标志的,所以char str1[ ] = “hello” 等效于char str2[ ] = {‘h’ , ‘e’ , ‘l’ , ‘l’ , ‘o’ , ‘\0’} 。strlen函数求的是字符串的实际长度,它求得方法是从开始到遇到第一个’\0’,如果你只定义没有给它赋初值,这个结果是不定的,它会从首地址一直找下去,直到遇到’\0’停止。而如果不在字符数组初始化的时候加上\0,那么strlen 得到的值就不是正确的数值,打印出来的结果也不是想要的结果。因此我们要避免这种情况,在初始化的时候要记得加上 \0,或者一次性赋初值。
5.strlen的结果要在运行的时候才能计算出来,是用来计算字符串的长度,不是类型占内存的大小。而大部分编译程序在编译的时候就把sizeof计算过了是类型或是变量的长度。
6.sizeof可以用类型做参数,strlen只能用char*做参数,且必须是以’‘\0’'结尾的。
原文链接:https://blog.csdn.net/zhengqijun_/article/details/51815081
边栏推荐
猜你喜欢

Markdown 1 - 图文音视频等

Go 事,Gopher 要学的数字类型,变量,常量,运算符 ,第2篇

一本通循环结构的程序设计第一章题解(1)

【Kaggle:UW-Madison GI Tract Image Segmentation】肠胃分割比赛:赛后复盘+数据再理解

手慢无!阿里亿级流量高并发系统设计核心原理全彩笔记现实开源

刷屏了!!!

Beijing, Shanghai and Guangzhou offline events丨The most unmissable technology gatherings at the end of the year are all gathered

云主机上的MongoDB被威胁,开启AUTH认证

元宇宙的六大支撑技术

ModelCoder状态机:对柴油机工况判断策略进行建模
随机推荐
Decoding Redis' most overlooked high CPU and memory usage issues
Using Baidu EasyDL to realize the recognition of the chef's hat of the bright kitchen
Go 事,Gopher 要学的数字类型,变量,常量,运算符 ,第2篇
13-GuliMall 基础篇总结
dolphinscheduler simple task definition and complex cross-node parameter transfer
无人艇轨迹跟踪的预设性能抗扰控制研究
MySQL查询性能优化
[PostgreSQL] - 存储结构及缓存shared_buffers
no matching host key type found. Their offer: ssh-rsa
58. 最后一个单词的长度
EasyNVR更新版本至(V5.3.0)后页面不显示通道配置该如何解决?
初级永磁直线电机双动子电流镜像容错控制
基于柔性人机接口的人机协调运动控制方法
R语言向前或者向后移动时间序列数据(自定义滞后或者超前的期数):使用dplyr包中的lag函数将时间序列数据向后移动一天(设置参数n为负值)
一本通循环结构的程序设计第一章题解(1)
关于香港高防IP需要关注的几个问题
一本通循环结构的程序设计题解(2)
How to solve the problem that the page does not display the channel configuration after the EasyNVR is updated to (V5.3.0)?
New:WebKitX ActiveX :::Crack
How to display an Excel table in the body of an email?