使用strncpy()函数出问题

TwenteMaster 2012-03-07 07:46:31
源代码:

/* Test function strncpy() */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
char destination[] = "This string will be replaced";
char source[] = "This string will be copied in part";
size_t n1 = 26; /* Number of characters to be copied */
strncpy(destination , source , n1);
printf("\n%s\n" , destination);

char* str = "MyString";
char* pStr = (char*)malloc(7 * sizeof(char));
size_t n2 = 6; /* Number of characters to be copied */
strncpy(pStr , str , n2);
printf("\n%s\n" , pStr);
return 0;
}


输出结果如下:
This string will be copieded

MyStri1

两个字符串的输出都与预想的不一样,这个是怎么回事?
...全文
258 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
自信男孩 2012-03-08
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 czh3642210 的回复:]
C/C++ code
char destination[] = "This string will be replaced";//这个的长度是28
strncpy(destination , source , n1);//运行这个只是将source中的前26个字符将
//destination的前26个字符覆盖了,但是destination后边还有两个字符ed;所以输出的时候是
//Thi……
[/Quote]
++字符串是遇到'\0'才会结束的。所以输出多余的"ed"后遇到了'\0'也就结束了。
第二个输出道理是一样的。你可以先对申请的空间进行初始化,使用memset();或者bzero();都可以。初始化为0.
ningto.com 2012-03-08
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 tujiaw 的回复:]

第一个:destination这是常量不能给它赋值
第二个:malloc之后
memset(pStr, 0, 7 * sizeof(char));
[/Quote]
我错了, 应该是char *str = "aaaaaa";
赵4老师 2012-03-08
  • 打赏
  • 举报
回复
strncpy(d,s,n);d[n]=0;
kason2011 2012-03-07
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 czh3642210 的回复:]

第二个基本上就是楼上写的,、、、
这两个最主要的原因是,你copy过去的没有结束符,所以当你打印的时候会一直从字符串的首地址开始,直到遇到内存中的一个结束符
[/Quote]这才明白为什么要用memset
AnYidan 2012-03-07
  • 打赏
  • 举报
回复

char destination[] = "This string will been replaced";
char source[] = "This string will be copied in part";
size_t n1 = 26; /* Number of characters to be copied */
strncpy(destination , source , n1);
printf("\n%s\n" , destination);


测试用例不当
zsc_ericluo 2012-03-07
  • 打赏
  • 举报
回复
LS解释很清楚了
++
面包大师 2012-03-07
  • 打赏
  • 举报
回复
第二个基本上就是楼上写的,、、、
这两个最主要的原因是,你copy过去的没有结束符,所以当你打印的时候会一直从字符串的首地址开始,直到遇到内存中的一个结束符
面包大师 2012-03-07
  • 打赏
  • 举报
回复
char destination[] = "This string will be replaced";//这个的长度是28
strncpy(destination , source , n1);//运行这个只是将source中的前26个字符将
//destination的前26个字符覆盖了,但是destination后边还有两个字符ed;所以输出的时候是
//This string will be copied(ed),而不是This string will be copied
ningto.com 2012-03-07
  • 打赏
  • 举报
回复
第一个:destination这是常量不能给它赋值
第二个:malloc之后
memset(pStr, 0, 7 * sizeof(char));

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧