网站建设流程及细节,心雨在线高端网站建设专业,数字创意设计包括哪些方面,怎么做钓鱼网站生成器再前几篇的博客中大家可能发现了#xff0c;strcpy#xff0c;strcat#xff0c;strcmp 这三个函数在使用时对源字符串没有长度限制#xff0c;几乎是将源字符串的内容全部进行操作。在VS编译器中的这些函数显得不安全了#xff0c;因此VS会提醒你在其后加上 _s #x…再前几篇的博客中大家可能发现了strcpystrcatstrcmp 这三个函数在使用时对源字符串没有长度限制几乎是将源字符串的内容全部进行操作。在VS编译器中的这些函数显得不安全了因此VS会提醒你在其后加上 _s 或者在首行加上 #define _CRT_SECURE_NO_WARNINGS。
由于这些原因C语言又引入了 strncpystrncatstrncmp 等长度受限制的一组相对来说比较安全的函数。 ⚡strncpy Copies the first num characters of source to destination. If the end of the source C string(which is signaled by a null-character) is found before num characters have been copied,destination is padded with zeros until a total of num characters have been written to it.拷贝num个字符从源字符串到目标空间。如果源字符串的长度小于num则拷贝完源字符串之后在目标的后边追加\0直到num个。
strncpy的基本使用
#define _CRT_SECURE_NO_WARNINGS
#include stdio.h
#includestring.hint main()
{char arr1[] abcdef;char arr2[5] { 0 };strncpy(arr2, arr1, 3);printf(%s\n, arr2);return 0;
} 运行结果如下 ⚡strncat strncat 函数再追加完后自动会在其后补上一个 \0。如果输入的追加长度大于源字符串中的字符个数那么在追加完源字符串包括 \0 后不会再凑剩下的字符了。
代码示例如下
#define _CRT_SECURE_NO_WARNINGS
#include stdio.h
#includestring.hint main()
{char arr1[20] hello \0xxxxx;char arr2[] abcdef;strncat(arr1, arr2, 3);printf(%s\n, arr1);return 0;
}
运行结果如下 strncat 可以自己给自己追加。 ⚡strncmp 比较到出现另个字符不一样或者一个字符串结束或者num个字符全部比较完。#define _CRT_SECURE_NO_WARNINGS
#include stdio.h
#includestring.hint main()
{char arr1[] abcdef;char arr2[] abc;int ret strncmp(arr1, arr2, 3);printf(%d\n, ret);return 0;
} 运行结果如下 当然在VS中 strcpy_sstrcat_sstrcmp_s 也可以用来作为长度受限的函数。 感谢大家能够看完这篇博客创作时长小伙伴们觉得我的博客对你有帮助不妨留下你的点赞的收藏关注我带你了解不一样的C语言。