strncpy函数学习
来源:互联网 发布:天天生鲜项目源码 编辑:程序博客网 时间:2024/06/16 01:08
- 原型:
char* strncpy(char* string1, char* string2, int n)
- 说明:用字符串string2的前n个字符覆盖字符串string1的前n个字符,如果string1本来有数据,会被覆盖
- 返回值类型: 返回覆盖后字符串的指针,也就是string1的指针
int main(){ char a[] = "123456789"; char b[] = "abcd"; char* p = strncpy(a, b, 2); //只复制了b中的两个字符 cout << a << endl; cout << p << endl; cout << sizeof(a) << endl; return 0;}
运行结果:
不要以为问题就结束了,没那么简单,看下面代码
int main(){ char a[] = "123456789"; char b[] = "abcd"; char c[] = "efghijklm"; cout << "操作前:" << endl; cout << "a: " << a << endl << "b: " << b << endl << "c: " << c << endl << endl; cout << "复制b中两个字符到a " << endl; char* t1 = strncpy(a, b, 2); cout << "a: " << a << endl; cout << "返回值: " << t1 << endl; cout << "sizeof(a): " << sizeof(a) << endl; cout << "strlen(a): " << strlen(a) << endl << endl; cout << "复制c中全部字符到b" << endl; cout << b << endl; char* t2 = strncpy(b, c, strlen(c)); cout << "b: " << b << endl << "返回值: " << t2 << endl; cout << "sizeof(b): " << sizeof(b) << endl; cout << "strlen(b): " << strlen(b) << endl; return 0;}
运行结果:
当复制c中字符到b中时,结果超过了预期,b的长度变成了14,但是b数组总长度只申请了5,没有出现访问越界,至少没有报错,是怎么回事?
于是又有了下面的代码:
int main(){ char b[] = "abcd"; char c[] = "efghijklm"; cout << "操作前:" << endl; cout << "b: " << b << endl << "c: " << c << endl << endl; cout << "复制c中全部字符到b" << endl; cout << b << endl; char* t2 = strncpy(b, c, strlen(c)); cout << "b: " << b << endl << "返回值: " << t2 << endl; cout << "sizeof(b): " << sizeof(b) << endl; cout << "strlen(b): " << strlen(b) << endl; return 0;}
运行结果:
- 我们看到输出了乱码,表明发生了越界
- 因为b中最多只能容纳5个字符,包括终结符,复制时,终结符被覆盖,输出则不知道结尾,出现了越界
- 至于没有提示错误,可能是编译器内部做了优化,本次测试用的是
codeblock
注:
使用该函数时,n的选取一定 不要超过string1的长度范围。覆盖后不要覆盖掉终结符
。
0 0
- strncpy函数学习
- strncpy函数
- strncpy() 函数
- strncpy() 函数
- strncpy函数
- strncpy函数
- 函数 strncpy
- strncpy()函数
- strncpy函数
- strncpy()函数
- strncpy函数
- strncpy()函数
- strncpy函数
- 字符串函数strncpy
- strncpy函数原型
- strcpy与strncpy函数
- strcpy,strncpy函数
- strncpy函数的用法
- android通过Jni加载so库遇到UnsatisfiedLinkError问题!!!
- 人工智能动态整理
- BFS_1
- C++STL之set容器
- 文本复制后自动实现跳转的js代码
- strncpy函数学习
- ByteBuffer的Put和Get的用法和要注意的细节
- block(块级元素)和 inline(内联元素) 的区别
- TestFlight,app正式上线之前的测试环节。
- java中的try-catch-finally的处理流程介绍
- ACM模板——最长公共子序列 LCS
- matlab中dist函数使用方法
- HDU 1075 字典树 树搜索 逆路径输出单词
- Get请求Demo