自己写strncpy 复制\0
时间: 2023-11-18 11:50:05 浏览: 72
自己写strncpy函数复制'\0'的方法是在复制过程中判断源字符串是否已经复制完毕,如果复制完毕则手动在目标字符串的最后添加'\0'。以下是一个示例的自定义strncpy函数的实现:
```c
char* my_strncpy(char* dest, const char* src, int len) {
assert(dest != NULL && src != NULL);
char* temp = dest;
int i = 0;
while (i < len && (*temp = *src) != '\0') {
temp++;
src++;
i++;
}
if (i == len) {
*(temp - 1) = '\0';
} else {
*temp = '\0';
}
return dest;
}
```
这个函数会在复制过程中判断是否已经复制了指定的字符数,如果复制完毕则在目标字符串的最后添加'\0',否则不添加。
#### 引用[.reference_title]
- *1* [C语言strcpy、strncpy函数是否会复制‘\0‘结束符](https://blog.csdn.net/DRAXY/article/details/123759783)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* *3* [最常见的strncpy函数的缺陷,‘\0‘问题](https://blog.csdn.net/weixin_44261839/article/details/113995388)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文