当前位置:网站首页>深度剖析 string —— strcpy & strncpy
深度剖析 string —— strcpy & strncpy
2022-07-21 05:04:00 【十里坡小白】
系列文章目录
深度剖析:strcat & strncat
深度剖析:strchr & strstr
深度剖析:strcmp & strncmp
深度剖析:strcpy & strncpy
深度剖析:strlen & strtok
深度剖析:memcpy & memmove
深度剖析:memset & memcmp
前言
库函数string是我们经常使用也是非常重要的代码,我将会对常用的函数的用法和实现原理进行深度剖析
一、strcpy
1.调用结构
char *strcpy(char *dest, const char *src);
2.使用详解
strcpy:把 src 所指向的字符串复制到 dest
原理详解:
- 源字符串必须以’\0’结束
- 会将源字符串中的’\0’拷贝到目标空间
- 目标空间必须足够大,以确保能存放源字符串(不够大也依然能全部拷贝,但会报错)
- 目标空间必须可变(不能是常量字符串)
3.源码剖析
char *Strcpy(char *dest, const char *src) {
//把 src 所指向的字符串复制到 dest
assert(dest && src); //防止传入空指针
char *start = dest; //记录起始位置
while ((*dest++ = *src++) != '\0'); //拷贝字符串
return start; //返回起始位置
}
二、strncpy
1.调用结构
char *strncpy (char *dest, const char *src, size_t n);
2.使用详解
strncpy:把 src 所指向的字符串复制到 dest,最多复制 n 个字符
原理详解:
- 拷贝num个字符从源字符串到目标空间
- 如果源字符串的长度小于num,则拷贝完源字符串之后,在目标的后边追加0,直到num个
3.源码剖析
char *Strncpy(char *dest, const char *src, int len) {
//把 src 所指向的字符串复制到 dest,最多复制 n 个字符
char *start = dest;
while (len-- && (*dest++ = *src++) != 0); // len先交付结果再--
if (len) {
// 保护代码,后面全部补0
while (--len) {
// len的位置有'\0'
*dest++ = '\0';
}
}
return start;
}
边栏推荐
- Hetai 32 onenet WiFi module - Hetai MCU data cloud through mqtt protocol (II)
- 深度剖析 —— 结构体
- P1364 医院设置
- Stack, queue, linked list
- ES聚合统计语法
- Exclusive locking of this profile failed. Another running VMware process may be using a profile.
- conda安装datasets避免冲突命令
- Isempty and isblank
- 深度剖析 string —— strlen & strtok
- OneNote plug-in, cloud expansion
猜你喜欢
mask rcnn 加载权重报错
UNET reproduction and environment configuration (including dataset)
Database connection failed
合泰32-Onenet-WiFi模块-合泰单片机通过MQTT协议数据上云(一)
3.从零开始paddlepaddle之基本模型构建(与keras和pytorch比对)
Hetai ht32 -- taojingchi tjc--t0 serial port screen learning notes (II)
枚举的例子
合泰HT32--淘晶驰TJC--T0串口屏学习笔记(二)
Hetai 32 onenet WiFi module - Hetai MCU data cloud through mqtt protocol (II)
Hetai ht32--4spi drive 0.96 inch OLED display implementation
随机推荐
OLED(经典0.96英寸)--4SPI--SSD1306控制原理(含常用芯片_oled例程)
合泰32-Onenet-WiFi模块-合泰单片机通过MQTT协议数据上云(一)
mac brew install mysql 安装步骤
Kingbase conversion time
桶排序,冒泡排序,快速排序
Some pits encountered in running TDD net
4. 10 lines of code MNIST handwritten numeral recognition of paddlepaddle
cv2的相关函数
Pytorch Basics
C. Binary String(求前缀和)
Mac brew install MySQL installation steps
合泰32-Onenet-WiFi模块-合泰单片机通过MQTT协议数据上云(二)
洛谷P1119 灾后重建(Floyd)
我的第一篇博客
猫狗图片资源
(environment configuration) TDD net
4.paddlepaddle之10行代码mnist手写数字识别
Display method of front desk serial number
codeforces 1647A Madoka and Math Dad
(笔记)吴恩达深度学习L4W2